JavaScript Basics - ApplefaceLisa/WebDev GitHub Wiki
JavaScript Basics
JavaScript and HTML DOM Reference
String Methods
All string methods return a new string. They don't modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only replaced.
String Length
The length property returns the length of a string:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length; // 26
Finding a String in a String
- indexOf()
The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string:
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate"); // 7
- lastIndexOf()
The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate"); // 21
Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found.
Searching for a String in a String
The search() method searches a string for a specified value and returns the position of the match:
var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate"); // 7
Did You Notice?
The two methods, indexOf() and search(), are equal.
They accept the same arguments (parameters), and they return the same value.
The two methods are equal, but the search() method can take much more powerful search values.
You will learn more about powerful search values in the chapter about regular expressions.
Extracting String Parts
There are 3 methods for extracting a part of a string:
- slice(start, end)
- substring(start, end)
- substr(start, length)
The slice() Method
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the starting index (position, inclusive), and the ending index (position, exclusive).
This example slices out a portion of a string from position 7 to position 13:
var str = "Apple, Banana, Kiwi";
var res = str.slice(7, 13); // "Banana"
If a parameter is negative, the position is counted from the end of the string.
This example slices out a portion of a string from position -12 to position -6:
var str = "Apple, Banana, Kiwi";
var res = str.slice(-12, -6); // "Banana"
If you omit the second parameter, the method will slice out the rest of the string:
var res = str.slice(7); // "Banana, Kiwi" var res = str.slice(-4); // "Kiwi"
Negative positions do not work in Internet Explorer 8 and earlier.
The substring() Method
substring() is similar to slice().
The difference is that substring() cannot accept negative indexes.
var str = "Apple, Banana, Kiwi";
var res = str.substring(7, 13); // "Banana"
If you omit the second parameter, substring() will slice out the rest of the string.
The substr() Method
substr() is similar to slice().
The difference is that the second parameter specifies the length of the extracted part.
var str = "Apple, Banana, Kiwi";
var res = str.substr(7, 6); // "Banana"
If the first parameter is negative, the position counts from the end of the string.
var str = "Apple, Banana, Kiwi";
var res = str.substr(-4, 3); // "Kiw"
The second parameter can not be negative, because it defines the length.
If you omit the second parameter, substr() will slice out the rest of the string.
var str = "Apple, Banana, Kiwi";
var res = str.substr(12); // "a, Kiwi"
Replacing String Content
The replace() method replaces a specified value with another value in a string. It does not change the string it is called on. It returns a new string.
str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3Schools"); // "Please visit W3Schools!"
The replace() method can also take a regular expression as the search value.
By default, the replace() function replaces only the first match. To replace all matches, use a regular expression with a g flag (for global match):
str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/, "W3Schools"); // "Please visit W3Schools and Microsoft!"
str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/g, "W3Schools"); // "Please visit W3Schools and W3Schools!"
Converting to Upper and Lower Case
A string is converted to upper case with toUpperCase():
var text1 = "Hello World!"; // String
var text2 = text1.toUpperCase(); // "HELLO WORLD!"
A string is converted to lower case with toLowerCase():
var text1 = "Hello World!"; // String var text2 = text1.toLowerCase(); // "hello world!"
Joint two or more Strings
concat() joins two or more strings:
var text1 = "Hello";
var text2 = "World";
text3 = text1.concat(" ", text2); // "Hello World!"
The concat() method can be used instead of the plus operator. These two lines do the same:
var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ", "World!");
Extracting String Characters
There are 2 safe methods for extracting string characters:
- charAt(position)
- charCodeAt(position)
The charAt() Method
The charAt() method returns the character at a specified index (position) in a string:
var str = "HELLO WORLD";
str.charAt(0); // returns "H"
The charCodeAt() Method
The charCodeAt() method returns the unicode of the character at a specified index in a string:
var str = "HELLO WORLD";
str.charCodeAt(0); // returns 72
Accessing a String as an Array is Unsafe
You might have seen code like this, accessing a string as an array:
var str = "HELLO WORLD";
str[0]; // returns H
This is unsafe and unpredictable:
- It does not work in all browsers (not in IE5, IE6, IE7)
- It makes strings look like arrays (but they are not)
- str[0] = "H" does not give an error (but does not work)
If you want to read a string as an array, convert it to an array first.
Converting a String to an Array
A string can be converted to an array with the split() method:
var txt = "a,b,c,d,e"; // String
var arr = txt.split(","); // Split on commas, arr = ['a','b','c','d','e'].
txt.split(" "); // Split on spaces
txt.split("|"); // Split on pipe
If the separator is omitted, the returned array will contain the whole string in index [0]:
var txt = "a,b,c,d,e";
var arr = txt.split();
console.log(arr[0]); // "a,b,c,d,e"
If the separator is "", the returned array will be an array of single characters:
var txt = "a,b,c,d,e";
var arr = txt.split(""); // arr = ['a',',','b',',','c',',','d',',','e']
var txt = "Hello"; // String
txt.split(""); // Split in characters, ['H','e','l','l','o']
JavaScript Numbers
JavaScript Numbers are Always 64-bit Floating Point.
JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard.
This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63.
Precision
Integers (numbers without a period or exponent notation) are considered accurate up to 15 digits.
var x = 999999999999999; // x will be 999999999999999
var y = 9999999999999999; // y will be 10000000000000000
The maximum number of decimals is 17.
Floating point arithmetic is not always 100% accurate:
var x = 0.2 + 0.1; // x will be 0.30000000000000004
To solve the problem above, it helps to multiply and divide:
var x = (0.2 * 10 + 0.1 * 10) / 10; // x will be 0.3
Infinity
Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number.
Division by 0 (zero) also generates Infinity:
var x = 2 / 0; // x will be Infinity
var y = -2 / 0; // y will be -Infinity
Infinity is a number: typeof Infinity returns number.
typeof Infinity; // returns "number"
NaN - Not a Number
NaN is a JavaScript reserved word indicating that a number is not a legal number.
Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number):
var x = 100 / "Apple"; // x will be NaN (Not a Number)
However, if the string contains a numeric value , the result will be a number:
var x = 100 / "10"; // x will be 10
You can use the global JavaScript function isNaN() to find out if a value is a number.
var x = 100 / "Apple";
isNaN(x); // returns true because x is Not a Number
If you use NaN in a mathematical operation, the result will also be NaN.
Number Methods
- toString()
- toExponential()
- toFixed()
- toPrecision()
- valueOf()
toString()
returns a number as a string.
var x = 123;
x.toString(); // returns "123" from variable x
(123).toString(); // returns "123" from literal 123
(100 + 23).toString(); // returns "123" from expression 100 + 23
you can use the toString() method to output numbers as base 16 (hex), base 8 (octal), or base 2 (binary):
var myNumber = 128;
myNumber.toString(16); // returns "80"
myNumber.toString(8); // returns "200"
myNumber.toString(2); // returns "10000000"
toExponential()
returns a string, with a number rounded and written using exponential notation.
A parameter defines the number of characters behind the decimal point:
var x = 9.656;
x.toExponential() // returns "9.656e+0"
x.toExponential(2); // returns "9.66e+0"
x.toExponential(4); // returns "9.6560e+0"
x.toExponential(6); // returns "9.656000e+0"
var x = 1999.656;
x.toExponential() // returns "1.999656e+3"
x.toExponential(2); // returns "2.00e+3"
x.toExponential(4); // returns "1.9997e+3"
x.toExponential(6); // returns "1.999656e+3"
The parameter is optional. If you don't specify it, JavaScript will not round the number.
toFixed()
returns a string, with the number written with a specified number of decimals:
var x = 9.656;
x.toFixed(0); // returns "10"
x.toFixed(2); // returns "9.66"
x.toFixed(4); // returns "9.6560"
x.toFixed(6); // returns "9.656000"
toFixed(2) is perfect for working with money.
toPrecision()
returns a string, with a number written with a specified length:
var x = 9.656;
x.toPrecision(); // returns "9.656"
x.toPrecision(2); // returns "9.7"
x.toPrecision(4); // returns "9.656"
x.toPrecision(6); // returns "9.65600"
valueOf()
returns a number as a number.
var x = 123;
x.valueOf(); // returns 123 from variable x
(123).valueOf(); // returns 123 from literal 123
(100 + 23).valueOf(); // returns 123 from expression 100 + 23
In JavaScript, a number can be a primitive value (typeof = number) or an object (typeof = object).
The valueOf() method is used internally in JavaScript to convert Number objects to primitive values.
There is no reason to use it in your code.
All JavaScript data types have a valueOf() and a toString() method.
Converting Variables to Numbers
There are 3 JavaScript methods that can be used to convert variables to numbers:
- The Number() method : Returns a number, converted from its argument.
- The parseInt() method : Parses its argument and returns an integer.
- The parseFloat() method : Parses its argument and returns a floating point number.
These methods are not number methods, but global JavaScript methods. JavaScript global methods can be used on all JavaScript data types.
// Number() can be used to convert JavaScript variables to numbers:
x = true;
Number(x); // returns 1
x = false;
Number(x); // returns 0
x = new Date();
Number(x); // returns 1404568027739
x = "10"
Number(x); // returns 10
x = "10 20"
Number(x); // returns NaN
// parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned:
parseInt("10"); // returns 10
parseInt("10.33"); // returns 10
parseInt("10 20 30"); // returns 10
parseInt("10 years"); // returns 10
parseInt("years 10"); // returns NaN
// parseFloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned:
parseFloat("10"); // returns 10
parseFloat("10.33"); // returns 10.33
parseFloat("10 20 30"); // returns 10
parseFloat("10 years"); // returns 10
parseFloat("years 10"); // returns NaN
Number Properties
- Property Description
- MAX_VALUE Returns the largest number possible in JavaScript
- MIN_VALUE Returns the smallest number possible in JavaScript
- NEGATIVE_INFINITY Represents negative infinity (returned on overflow)
- NaN Represents a "Not-a-Number" value
- POSITIVE_INFINITY Represents infinity (returned on overflow)
Number properties belongs to the JavaScript's number object wrapper called Number.
These properties can only be accessed as Number.MAX_VALUE.
var x = Number.MAX_VALUE; // 1.7976931348623157e+308
var x = Number.MIN_VALUE; // 5e-324
var x = Number.NEGATIVE_INFINITY; // -Infinity
var x = Number.NaN; // NaN
var x = Number.POSITIVE_INFINITY; // Infinity
Using myNumber.MAX_VALUE, where myNumber is a variable, expression, or value, will return undefined:
var x = 6;
var y = x.MAX_VALUE; // y becomes undefined
JavaScript Number Reference
Array Methods
-
toString() : converts an array to a string of (comma separated) array values.
-
join() : joins all array elements into a string. It behaves just like toString(), but in addition you can specify the separator.
-
pop() : removes the last element from an array, and returns the value that was "popped out".
-
push() : adds a new element to an array (at the end) and returns the new array length.
-
shift() : removes the first array element and "shifts" all other elements to a lower index, returns the string that was "shifted out".
-
unshift() : adds a new element to an array (at the beginning), and "unshifts" older elements, and returns the new array length.
-
splice() : can be used to add new items to an array, or remove existing elements from array.
-
concat() : creates a new array by concatenating two or more arrays. eg: result = arr1.concat(arr2, arr3,...).
-
slice() : slices out a piece of an array into a new array. It does not remove any elements from the source array. eg.: result = arr.slice(n); result is arr[n:arr.length-1].
-
toString() : returns an array as a comma separated string. JavaScript automatically converts an array to a string when a primitive value is expected. eg.: you will get same result if do console.log(arr.toString()) and console.log(arr).
-
sort() : sorts an array alphabetically. Note: sorts values as strings. Example. Note: compare function.
-
reverse() : reverses the sequence of elements in an array. eg.: ["Banana", "Orange", "Apple", "Mango"].reverse() -> ["Mango", "Apple", "Orange", "Banana"].
Booleans
Truthy and Falsey
- Truthy: Something which evaluates to TRUE.
- Falsey: Something which evaluates to FALSE.
It’s mostly logical. One (1) is truthy, Zero (0) is falsey. An object of any kind (including functions, arrays, RegExp objects, etc.) is always truthy. The easiest way to determine if something is truthy is to determine that it’s not falsey.
There are only six falsey values in JavaScript: undefined, null, NaN, 0 (+0 and -0), "" (empty string), and false, of course.
Note: It is possible to explicitly wrap a primitive (string, number, null, undefined, boolean) in an object, which will make it truthy. For example, 0 (zero) is falsey, but new Number(0) is truthy. A scarier example is new Boolean(false) which is also truthy! Be careful. Only very rarely should you need to explicitly wrap primitives.
Type Conversion
RegExp
RegExp expression method
test() : searches a string for a pattern, and returns true or false, depending on the result. exec() : searches a string for a specified pattern, and returns the found text. If no match is found, it returns null.
JavaScript Errors - Throw and Try to Catch
- The try statement lets you test a block of code for errors.
- The catch statement lets you handle the error.
- The throw statement lets you create custom errors.
- The finally statement lets you execute code, after try and catch, regardless of the result.
The JavaScript statements try and catch come in pairs: try { Block of code to try } catch(err) { Block of code to handle errors }
The throw statement allows you to create a custom error. If you use throw together with try and catch, you can control program flow and generate custom error messages. example
The finally statement lets you execute code, after try and catch, regardless of the result: try { Block of code to try } catch(err) { Block of code to handle errors } finally { Block of code to be executed regardless of the try / catch result }
Error object
JavaScript has a built in error object that provides error information when an error occurs.
The error object provides two useful properties: name and message.
Debugging
Hoisting
Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function). JavaScript only hoists declarations, not initializations.
Strict Mode
"use strict"; Defines that JavaScript code should be executed in "strict mode".
The "use strict" directive is only recognized at the beginning of a script or a function.
Not Allowed in Strict Mode
- Using a variable, without declaring it.
- Using an object, without declaring it.
- Deleting a variable (or object).
- Deleting a function.
- Duplicating a parameter name.
- Octal numeric literals.
- Escape characters.
- Writing to a read-only property.
- Writing to a get-only property.
- Deleting an undeletable property.
- Use the string "eval" as a variable.
- Use the string "arguments" as a variable.
- Use with statement.
- Use eval() to create variables in the scope from which it was called.
Future reserved keywords are not allowed in strict mode. These are:
- implements
- interface
- let
- package
- private
- protected
- public
- static
- yield
Coding Style Guide
Best Practice
- Avoid Global Variables. Use local variables instead, and learn how to use closures.
- Always Declare Local Variables. Local variables must be declared with the var keyword, otherwise they will become global variables.
- Declarations on Top.
- Initialize Variables.
- Never Declare Number, String, or Boolean Objects. Declaring these types as objects, slows down execution speed, and produces nasty side effects.
- Don't Use new Object(), in other words:
- Use {} instead of new Object()
- Use "" instead of new String()
- Use 0 instead of new Number()
- Use false instead of new Boolean()
- Use [] instead of new Array()
- Use /()/ instead of new RegExp()
- Use function (){} instead of new Function()
- Beware of Automatic Type Conversions.
- Use === Comparison.
- Use Parameter Defaults.
- End Your Switches with Defaults.
- Avoid Using eval(). The eval() function is used to run text as code. In almost all cases, it should not be necessary to use it. Because it allows arbitrary code to be run, it also represents a security problem.
Proper Random Functions
-
This JavaScript function always returns a random number between min (included) and max (excluded):
function getRndInteger(min, max) { return Math.floor(Math.random() * (max - min) ) + min; }
-
This JavaScript function always returns a random number between min and max (both included):
function getRndInteger(min, max) { return Math.floor(Math.random() * (max - min + 1) ) + min; }
Performance
How to speed up your JavaScript code.
- Reduce Activity in Loops
- Reduce DOM Access
- Reduce DOM Size
- Avoid Unnecessary Variables
- Delay JavaScript Loading
- Avoid Using with
Credit
Thanks for W3School.