A variable is a name or identifier that represents data stored in computer memory. JavaScript data can have simple basic types: {Numeric, Character, String, Date, Time} or more complex types: {objects, images, collections}. Using variables you can create computations and then display the results.
Momentarily there are 4 ways to declare a variable in JavaScript. In next example we declare 4 variables in 4 different ways. Only first variable will have initial value, the other variables will have value: 'undefined':
// using "=" operator
first = 0
// using var keyword
var second
// using let keyword
let third
// using const keyword
const forth
A JavaScript variable can have a data type: 'numeric', 'string', 'boolean' or 'object'. To make the variable "salary" be of a numeric data type, we will simply assign a number using "=" operator. If the variable is not defined yet, it will be automatically created with initial value.
Next example show you a variations of assignment statements that create varianles using type inference without the keyword var, let or const.
//Declare an integer variable using type inference
salary = 1000;
//Alternatively, we can assign the variable a string value:
salary = "entry level";
//We can also assign it a Boolean value:
salary = true;
//We can also declare and assign a variable
//on the same line in order to make our code shorter:
salary = 1000;
//Later in our code, we might decide we want to change
//the value of our variable. To do that,
//we simply assign our variable a new value:
salary = 2000;
Note: By changing the value of a variable we can also change its data type. We can re-declare a variable in JavaScript using "var" but not using "let" or "const". For new JavaScript code we recommend to quit using "var" that is deprecated.
In next example variable "test" is declared several times using keyword "var".
var test = "test"
console.log(test) // 'test'
var test;
console.log(test) // 'test'
var test = 0;
console.log(test) // 0
It is not possible to declare a variable several times using "let". It is more logical not to be able to re-declare a variable. Unfortunately you can still use assignment before declaration. Next example demonstrate a property of JavaScript called "hoisting". You can use something before it is defined.
Next example should fail because we redeclare a variable that exist using let.
a = 30;
console.log(a); //expect: 30
let a;
console.log(a); //expect: 30
Note: JavaScript is difficult to defend sometimes. Don't be discouraged it is still a good language. It just need some fixes that will be done eventually in the future. Nobody is perfect. All you need to do is… avoid traps. Do not change the meaning nor the type of variables in your code. It is a bad practice.
We can declare more than one variable into a single statement. For each variable we can assign a different value. Multiple declarations are separated by comma and terminated by ";".
//declare 3 variables on single line
let driver = "John", car = "Acura", year = "1999";
//declare 3 variables in one single statement
let
driver = "Xena",
car = "Porsche",
year = "2015";
let test1, test2 = "test";
console.log(test1) // undefined
console.log(test2) // 'test'
The correct way to declare multiple variables having same initial value must use "transitivity" property of assign operator:
let a = b = c = 10; //same initial value
console.log(a,b,c) //expect: 10, 10, 10
JavaScript is a dynamic language. That means the type of variable can be changed using assignment. Current type can be investigate using function typeof(). This can be useful if you wish to do some 'introspection before using operators on the wrong type.
JavaScript do not make a differentiation between integers and float numbers like other languages. There is only one numeric type in JavaScript: "number". In next example I try to change the type, but JavaScript is reporting the same type.
a = 30; // integer
type = typeof(a);
console.log(type); //'number'
a = 1.5; // float
type = typeof(a);
console.log(type); //'number'
JavaScript provides operators for standard arithmetic operations: addition, subtraction, multiplication, and division, 'along with modular division and negation. Usage of these operators is straightforward; here are some examples:
Operator | Description | Example | Result | ||
---|---|---|---|---|---|
+ | Addition | 5 + 2 |
7 | ||
- | Subtraction | 5 - 2 |
3 | ||
* | Multiplication | 5 * 2 |
10 | ||
/ | Division | 6 / 2 |
3 | ||
% | Modulus | 5 % 2 |
1 | ||
++ | Increment | let x = 5; |
6 | ||
-- | Decrement | let x = 5; |
4 | ||
** | Power | 2 ** 3; |
8 |
Operator | Short Name | Description |
---|---|---|
& | AND | Sets each bit to 1 if both bits are 1. |
| | OR | Sets each bit to 1 if one of two bits is 1. |
^ | XOR | Sets each bit to 1 if only one of two bits is 1. |
~ | NOT | Inverts all the bits. |
<< | LS | Shifts left by pushing zeros in from the right and let the leftmost bits fall off. |
>> | RS | Shifts right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off. |
Here is an HTML table explaining the bitwise operators in JavaScript with 4 byte examples
Value | A & B | A | B | A ^ B | A >> B | A << B |
---|---|---|---|---|---|
A | 1010 | 1010 | 1010 | 1101 | 1101 |
B | 0110 | 0110 | 0110 | 2 | 1 |
== | 0010 | 1110 | 1100 | 0011 | 1010 |
Bitwise operators are common in low level programming and less used in JavaScript. However you can use these operators for some high end use-cases.
Boolean type is a logical data type that can have values: true or false. If you use Boolean variables in numeric expressions they are automatically converted: true = 1 and false = 0.'Boolean types are also known as Logic types.
a = true;
console.log(typeof(a)); //Boolean
console.log(a); //true
a = a + 1;
console.log(a); //2
console.log(typeof(a)); //Numeric
Boolean operators in JavaScript are similar to C operators and are based on one or two characters.
//logical "and": &&
console.log(true && true); // true
console.log(true && false); // false
console.log(false && false);// false
//logical "or": ||
console.log(true || true); // true
console.log(true || false); // true
console.log(false || false);// false
//logical "not": !
console.log(!true); // false
console.log(!false); // true
The following values evaluate to false, also known as falsy values
A relation operator can be used to compare two values. Usually values are numeric but can be also strings or objects.'Relation operators are also known as comparison operators.'These operators produce a Boolean result. In the next table,'we use variable x = 5 to demonstrate various examples.
/* anonymous block */
{
let x = 5 // create a test fixture
console.log(x) // check variable x
/* test relation operator "==" */
console.log("is x equal to 5? ", x == 5)
}
Symbol | Description | Expression | Result |
---|---|---|---|
== | equal to | x == 8 | false |
x == 5 | true | ||
x == "5" | true | ||
=== | equal value and equal type | x === 5 | true |
x === "5" | false | ||
!= | not equal | x != 8 | true |
!== | not equal value or not equal type | x !== 5 | false |
x !== "5" | true | ||
x !== 8 | true | ||
> | greater than | x > 8 | false |
< | less than | x < 8 | true |
>= | greater than or equal to | x >= 8 | false |
<= | less than or equal to | x <= 8 | true |
String literals are surrounded by single quotes: '…' or double quotes "…". You can use quotes inside a string, as long as they don't match the quotes surrounding the string, 'otherwise you must use escape symbol "\" in front of quotes matching the surrounding quotes.
// Single quote inside double quotes
answer = "It's alright";
// Single quotes inside double quotes
answer = "He is called 'Johnny'";
// Double quotes inside single quotes
answer = 'He is called "Johnny"';
// Escape for single quote
answer = 'It\'s sister is famous!';
The process of joining two strings is also called concatenation. We create a new string using concatenate operator "+". Below is an example of concatenating two string variables.
//create two string variables
numberOfProducts = "five"
productType = "potato"
//create a third variable and assign to it a value
//by concatenating the two string variables we created earlier
inventory = numberOfProducts + productType
Templates are special string literals enclosed in back-quotes like: `demo`. There is a useful method for string manipulation called: "string interpolation". For this string template can use placeholders like: ${var}. A placeholder will be replace automatically by values.
//define object
let car = {type:"Fiat", model:"500", color:"white"}
//read object properties
console.log(`car type = ${car['type']}`)
console.log(`car model = ${car.model}`)
console.log(`car color = ${car.color}`)
let a = 5;
let b = 10;
console.log(`${a} + ${b} = ${a + b}`);
console.log(`2 * (${a} + ${b}) = ${2 * a + b}`);
Output:
5 + 10 = 15
2 * (5 + 10) = 20
A string is an object so it has methods. String methods can be call using the dot notation. For example if str="Hello World" is a sting then you can use method: 'split() like this: str.split(" ") and this will create an array of 2 words: ["Hello","World"]. The string was split in two parts and space (the separator) is discarded.
// define a string
let str = "hello world"
// use method split()
let arr = str.split(" ")
// display the result
console.log(arr); // ["hello", "world"]
There are 2 safe methods for extracting string characters:
// define a string
let str = "Hello World"
// safe access
w = str.charAt(6);
console.log(w); // W
// unsafe access
h = str[0]
console.log(h); // H
// safe access to code
c = str.charCodeAt(0);
console.log(c); //72
Note: Do not use a string like an array with index: str[0]. This is not safe, except if your string is using ASCII characters or printable Unicode symbols and no modifiers. If this is not true accessing a string character by index is a bad practice.
The string object has numerous predefined methods that are not in my scope to present. If you need a method you should consult the MDN reference documentation. To search this documentation type in google search box: MDN <function_name> for example: '"mdn charAt()", most of the time first hit will lead you to details about correct function.
Method | Description |
---|---|
charAt() | Returns the character at the specified index (position) |
charCodeAt() | Returns the Unicode of the character at the specified index |
concat() | Joins two or more strings, and returns a new joined strings |
endsWith() | Checks whether a string ends with specified string/characters |
fromCharCode() | Converts Unicode values to characters |
includes() | Checks whether a string contains the specified string/characters |
indexOf() | Returns the position of the first found occurrence of a specified value in a string |
lastIndexOf() | Returns the position of the last found occurrence of a specified value in a string |
localeCompare() | Compares two strings in the current locale |
match() | Searches a string for a match against a regular expression, and returns the matches |
repeat() | Returns a new string with a specified number of copies of an existing string |
replace() | Searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced |
search() | Searches a string for a specified value, or regular expression, and returns the position of the match |
slice() | Extracts a part of a string and returns a new string |
split() | Splits a string into an array of substrings |
startsWith() | Checks whether a string begins with specified characters |
substr() | Extracts the characters from a string, beginning at a specified start position, and through the specified number of character |
substring() | Extracts the characters from a string, between two specified indices |
toLocaleLowerCase() | Converts a string to lowercase letters, according to the host's locale |
toLocaleUpperCase() | Converts a string to uppercase letters, according to the host's locale |
toLowerCase() | Converts a string to lowercase letters |
toString() | Returns the value of a String object |
toUpperCase() | Converts a string to uppercase letters |
trim() | Removes white-space from both ends of a string |
Mozilla manual MDN: String Methods
Thouhj JavaScript do not declare type, a variable has type nevertheless. Sometimes you need to convert the value from one type to other type. This can be done using type coercion that is automatic (implicit) or explicit.
In the next example we concatenate strings with numbers. This is possible in JavaScript. However you must know JavaScript can surprise you from time to time with weird results. Do not let JavaScript rule you. I suggest to use explicit coercion.
/* default concatenation */
a = 3, b = "4"; // fixture
console.log(typeof(b)); // string
console.log(typeof(a)); // number
document.write('a, b = ', a, ',', b, '<br>');
document.write('a + b =', a + b,'<br>' ); // 34
document.write('b + a =', b + a,'<br>' ); // 34
/* automatic conversion */
document.write( 'b = ', b, '<br>')
document.write('b - a =', b - a,'<br>' ); // 1
document.write("b / 2 =", b / 2,'<br>'); // 2
document.write("b * 2 =", b * 2,'<br>'); // 8
document.write("++ b =", ++ b ,'<br>'); // 5
document.write("++ b =", -- b ,'<br>'); // 4
Do not relay on automatic implicit conversions. This may produce unexpected results or logical errors. It is possible to use explicit conversion instead. In the next example we use coercion function Number() to convert a string into a number
/* given fixture */
a = 3, b = "4";
/* explicit coercion */
c = a + Number(b); // 7
There are some special values in JavaScript that you must learn to understand possible strange situations when an unexpected result pop-up or an exception that you can not explain.
Read next: Functions