script tag in html file. You can place tag almost anywhere in HTML document.<script> tag contains JavaScript code which is automatically executed when the browser processes the tag.src attribute.| Code | Output |
|
```html
Before the script... ...After the script. ``` |
```console Before the script... // Alert will appear ...After the script. ``` |
| `src="path/"` | ```html ``` |
Statements are syntax constructs and commands that perform actions.
alert("Hello")
alert("World");
// or
alert("Hello");
alert("World");
// Both are correct.
// This comment occupies a line of its own
alert("Hello");
alert("World"); // This comment follows the statement
/* An example of.
a multiline comment.
*/
"use strict" or 'use strict' is located at the top of a script, the whole script works the “modern” way.1. 'use strict'
2.
3. funtion (){
4. ...
5. }
let keyword.var instead of let, you may find in old scripts.GOTOlet message; // Declaration
message = "Hello"; // Assigning
alert(message);
let wish = "Hello",
age = 25,
name = "Salman"; // Multiline Declaration, separated with comma
message = "World!"; // value changed, old value is removed from the variable
alert(message);
// repeated 'let' leads to an error
let message = "That"; // SyntaxError: 'message' has already been declared
$ and _.let USERNAME; // VALID
let userName; // VALID
let test123; // VALID
let 1a; // NOT VALID
let my-name; // NOT VALID hyphens '-' aren't allowed in the name
let let; // NOT VALID
let class; // NOT VALID
These keywords cannot be used as identifiers for variables, functions, classes, etc. anywhere in JavaScript source.
| break | case | catch | class |
| const | continue | debugger | default |
| delete | do | else | export |
| extends | false | final | finally |
| for | function | if | implements |
| import | in | instanceof | new |
| null | return | super | switch |
| this | throw | true | try |
| typeof | var | void | while |
| with |
b1 c5 d4 e3 f5 i5 n2 r1 s2 t5 v2 w2
The following are only reserved when they are found in strict mode code:
let (also reserved in const, let, and class declarations)staticyield (also reserved in generator function bodies)Only reserved in module code or async function bodies:
awaitFuture reserved words
| enum | implements | interface | package |
| private | protected | public |
The following are reserved as future keywords by older ECMAScript specifications (ECMAScript 1 till 3).
| abstract | boolean | byte | char |
| double | final | float | volatile |
| goto | int | long | native |
| short | synchronized | throws | transient |
Identifiers with special meanings
A few identifiers have a special meaning in some contexts without being reserved words of any kind. They include:
arguments (not a keyword, but cannot be declared as identifier in strict mode)as (import * as ns from “mod”)asynceval (not a keyword, but cannot be declared as identifier in strict mode)from (import x from “mod”)getofsetconst variable CANNOT be changed
const myBirthday = "18.04.1982";
myBirthday = "01.01.2001"; // error, can't reassign the constant!
There are eight basic data types in JavaScript.
| Number | BigInt | String | Boolean |
| Null | Undefined | Objects | Symbols |
Infinity, -Infinity and NaN.NaN as the result.Infinity represents the mathematical Infinity ∞. It is a special value that’s greater than any number.NaN represents a computational error. It is a result of an incorrect or an undefined mathematical operation, for instance.(253-1) (that’s 9007199254740991), or less than -(253-1) for negatives.alert(1 / 0); // Infinity
alert(Infinity); // Infinity
alert(“not a number” / 2); // NaN, such division is erroneous
alert(NaN + 1); // NaN alert(3 * NaN); // NaN alert(“not a number” / 2 - 1); // NaN
console.log(9007199254740991 + 1); // 9007199254740992 console.log(9007199254740991 + 2); // 9007199254740992
```js
if(NaN) console.log(true)
else console.log(false)
// false
if(undefined) console.log(true)
else console.log(false)
// false
if(null) console.log(true)
else console.log(false)
// false
if(0) console.log(true)
else console.log(false)
// false
if("") console.log(true)
else console.log(false)
// false
number type upto 1.7976931348623157 * 10308.BigInt value is created by appending n to the end of an integer.// the "n" at the end means it's a BigInt
const bigInt = 1234567890123456789012345678901234567890n;
let str = "Hello"; //Double quotes
let str2 = "Single quotes are ok too"; //Single quotes
let phrase = `can embed another ${str}`; //Backticks
alert(`the result is ${1 + 2}`); // the result is 3, embed an expression using backticks
true and false.let nameFieldChecked = true; // yes, name field is checked
let ageFieldChecked = false; // no, age field is not checked
let isGreater = 4 > 1;
alert(isGreater); // true (the comparison result is "yes")
null value does not belong to any of the types described above.null is not a reference to a non-existing object or a null pointer like in some other languages.let age = null;
console.log(typeof age); // object
undefined also stands apart. It makes a type of its own, just like null.undefined is “value is not assigned”.undefined:let age;
alert(age); // shows "undefined"
let age = 100;
// change the value to undefined
age = undefined; // explicitly assign undefined to a variable
alert(age); // "undefined"
Please go through this link for more on Objects
Please go through this link for more details on Symbols
typeof operator returns the type of the operand.typeof undefined // "undefined"
typeof 0 // "number"
typeof 10n // "bigint"
typeof true // "boolean"
typeof "foo" // "string"
typeof Symbol("id") // "symbol"
typeof Math // "object" (1)
typeof null // "object" (2) It'a an error, null is not an object. See null section
typeof alert // "function" (3)
To interact with user, we have alert, prompt and confirm functions in javascript.
string type.alert("Hello");
result = prompt(title, [default]);
// title = text to show the visitor.
// default = the initial value for the input field [optional].
let age = prompt('How old are you?', 100);
alert(`You are ${age} years old!`); // You are 100 years old!
NOTE:
[...]Square Brackets means Optional parameter
question and two buttons: OK and Cancel.true if OK is pressed and false otherwise.result = confirm(question);
let isBoss = confirm("Are you the boss?");
alert( isBoss ); // true if OK is pressed
String value instead of boolean value.string type.let value = true;
alert(typeof value); // boolean
value = String(value); // now value is a string "true"
alert(typeof value); // string
number type.NaN type.let str = "123";
alert(typeof str); // string
let num = Number(str); // becomes a number 123
alert(typeof num); // number
let age = Number("an arbitrary string instead of a number");
alert(age); // NaN, conversion failed
| Value | Becomes |
| `undefined` | `NaN` |
| `null` | `0` |
| `true and false` | `1` and `0` |
| `string` | Whitespaces (includes spaces, tabs `\t`, newlines `\n` etc.) from the start and end are removed. If the remaining string is empty, the result is `0`. Otherwise, the number is “read” from the string. An error gives `NaN`. |
alert( Number(" 123 ") ); // 123
alert( Number("123z") ); // NaN (error reading a number at "z")
alert( Number(true) ); // 1
alert( Number(false) ); // 0
0, an empty string, null, undefined, and NaN, become false.true.alert( Boolean(1) ); // true
alert( Boolean(0) ); // false
alert( Boolean("0") ); // true Zero is a string, not a number
alert( Boolean("hello") ); // true
alert( Boolean("") ); // false
+-*/% (NOT related to percent)**alert( 5 + 2 ); // 7,
alert( 8 - 3 ); // 5,
alert( 8 * 2 ); // 16,
alert( 5 / 2 ); // 2, the quotient of 5 divided by 2
alert( 8 % 2 ); // 0, the remainder of 8 divided by 2
alert( 2 ** 4 ); // 16, 2 to the power of 4.
alert( 4 ** (1/2) ); // 2 (power of 1/2 is the same as a square root)
alert( 8 ** (1/3) ); // 2 (power of 1/3 is the same as a cubic root)
+ is the only operator that supports strings in such a way. Other arithmetic operators work only with numbers and always convert their operands to numbers.+ applied to a single value, doesn’t do anything to numbers. But if the operand is not a number, the unary plus converts it into a number.let s = "my" + "string";
alert(s); // mystring
// ---->> BINARY <<-----
alert( '1' + 2 ); // "12"
alert( 2 + '1' ); // "21"
alert( 6 - '2' ); // 4, converts '2' to a number
alert( '6' / '2' ); // 3, converts both operands to numbers
// ---->> UNARY <<-----
// No effect on numbers
let x = 1;
alert( +x ); // 1
let y = -2;
alert( +y ); // -2
// Converts non-numbers to numbers
alert( +true ); // 1
alert( +"" ); // 0
let apples = "2";
let oranges = "3";
// both values converted to numbers before the binary plus
alert( +apples + +oranges ); // 5
// the longer variant
// alert( Number(apples) + Number(oranges) ); // 5
14 which is higher than the 11 of “addition” (binary plus). That’s why, in the expression "+apples + +oranges", unary pluses work before the addition.14 is High priority4 is low priority than 14| Preccedence | name | Sign |
|---|---|---|
| 14 | unary plus | `+` |
| 14 | unary negation | `-` |
| 13 | exponentiation | `**` |
| 12 | multiplication | `*` |
| 12 | division | `/` |
| 11 | addition | `+` |
| 11 | subtraction | `-` |
| ... | ... | `...` |
| 2 | assignment | `=` |
| ... | ... | `...` |
/=, -=, etc.let n = 2;
n += 5; // now n = 7 (same as n = n + 5)
n *= 2; // now n = 14 (same as n = n * 2)
alert( n ); // 14
// -------------------
n = 2;
n *= 3 + 5; // right part evaluated first, same as n *= 8
alert( n ); // 16
++ increases a variable by 1. It is in postfix form.-- decreases a variable by 1. It is in prefix form.5++ will give an error.let counter = 2;
counter++; // works the same as counter = counter + 1, but is shorter
alert( counter ); // 3
counter = 2;
counter--; // works the same as counter = counter - 1, but is shorter
alert( counter ); // 1
These operators are used very rarely, when we need to fiddle with numbers on the very lowest (bitwise) level.
& )| )^ )~ )<< )>> )>>> )You can read the Bitwise Operators in this MDN docs.
let a = (1 + 2, 3 + 4);
alert( a ); // 7 (the result of 3 + 4)
//the first expression 1 + 2 is evaluated and its result is thrown away. Then, 3 + 4 is evaluated and returned as the result.
a > b a < ba >= b, a <= ba == ba != bAll comparisions operators return a boolean value.
alert( 2 > 1 ); // true (correct)
alert( 2 == 1 ); // false (wrong)
alert( 2 != 1 ); // true (correct)
let result = 5 > 4; // assign the result of the comparison
alert( result ); // true
alert( 'Z' > 'A' ); // true
alert( 'Glow' > 'Glee' ); // true
alert( 'Bee' > 'Be' ); // true
The algorithm to compare two strings is simple:
In the first example above, the comparison 'Z' > 'A' gets to a result at the first step.
The second comparison 'Glow' and 'Glee' needs more steps as strings are compared character-by-character:
G is the same as G.
l is the same as l.
o is greater than e. Stop here. The first string is greater.
alert( '2' > 1 ); // true, string '2' becomes a number 2
alert( '01' == 1 ); // true, string '01' becomes a number 1
// for boolean values, true becomes 1 and false becomes 0.
alert( true == 1 ); // true
alert( false == 0 ); // true
let a = 0;
alert( Boolean(a) ); // false
let b = "0";
alert( Boolean(b) ); // true
alert(a == b); // true!
=== checks the equality without type conversion.alert( 0 === false ); // false
alert( null === undefined ); // false ---> strict equality
alert( null == undefined ); // true ---> strict equality
// null vs 0
alert( null > 0 ); // (1) false
alert( null == 0 ); // (2) false
alert( null >= 0 ); // (3) true
alert( undefined > 0 ); // false (1)
alert( undefined < 0 ); // false (2)
alert( undefined == 0 ); // false (3)
if statement evaluates a condition in parentheses and, if the result is true, executes a block of code.? statement instead of if statements.if statement fails then else block is execute. if statement may contain optional else block.else if statement test several variants of a condition.? looks like this let result = condition ? value1 : value2;let year = prompt('In which year was ECMAScript-2015 specification published?', '');
if (year == 2015) alert( 'You are right!' );
// if and else
if (year == 2015) {
alert( 'You guessed it right!' );
} else {
alert( 'How can you be so wrong?' ); // any value except 2015
}
// if and else if
//year = 2015
if (year < 2015) {
alert( 'Too early...' );
} else if (year > 2015) {
alert( 'Too late' );
} else {
alert( 'Exactly!' ); // this one may execute
}
// conditional operator ?
let accessAllowed;
let age = prompt('How old are you?', '');
if (age > 18) {
accessAllowed = true;
} else {
accessAllowed = false;
}
alert(accessAllowed);
// can be written in ? operator
let accessAllowed = (age > 18) ? true : false;
|| (OR), && (AND), ! (NOT), ?? (Nullish Coalescing).|| OR operator => If any of its arguments are true, it returns true, otherwise it returns false.|| operator evaluates operands from left to right. For each operand, converts it to boolean. If the result is true, stops and returns the original value of that operand.&& AND operator returns true if both operands are truthy and false otherwise.false, stops and returns the original value of that operand.&& is higher than OR ||.! (NOT) operator returns reverse value.!! Double NOT is sometimes used for converting a value to boolean type. Similar to Boolean("non-empty string")! is the highest of all logical operators, so it always executes first, before && or ||.// ||
alert( true || true ); // true
alert( false || true ); // true
alert( true || false ); // true
alert( false || false ); // false
// &&
alert( true && true ); // true
alert( false && true ); // false
alert( true && false ); // false
alert( false && false ); // false
// !
alert( !true ); // false
alert( !0 ); // true
null nor undefined.a ?? b is:
- if a is defined, then a,
- if a isn’t defined, then b.?? operator is the same as ||. only a bit higher than ? and =.|| or && without explicit parentheses.// set height=100, if height is null or undefined
height = height ?? 100;
false.while (condition) {
// code
// so-called "loop body"
}
let i = 0;
while (i < 3) { // shows 0, then 1, then 2
alert( i );
i++;
}
do {
// loop body
} while (condition);
let i = 0;
do {
alert( i );
i++;
} while (i < 3);
for (begin; condition; step) {
// ... loop body ...
}
for (let i = 0; i < 3; i++) { // shows 0, then 1, then 2
alert(i);
}
let sum = 0;
while (true) {
let value = +prompt("Enter a number", '');
if (!value) break; // (*)
sum += value;
}
alert( 'Sum: ' + sum );
continue.for (let i = 0; i < 10; i++) {
// if true, skip the remaining part of the body
if (i % 2 == 0) continue;
alert(i); // 1, then 3, 5, 7, 9
}
break/continue to escape a nested loop to go to an outer one.outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
let input = prompt(`Value at coords (${i},${j})`, '');
// if an empty string or canceled, then break out of both loops
if (!input) break outer; // (*)
// do something with the value...
}
}
alert('Done!');
if else if statements.x is checked for a strict equality.switch(x) {
case 'value1': // if (x === 'value1')
...
[break]
case 'value2': // if (x === 'value2')
...
[break]
default:
...
[break]
}
function is some block of code, to be called many times without repetition.function declaration.function is should be declared first, before calling it.alert(message); // prebuilt function
prompt(message, default); // prebuilt function
confirm(question); // prebuilt function
function showMessage() { // custom function
alert( 'Hello everyone!' );
}
showMessage();
showMessage();
function showMessage() {
let message = "Hello, I'm JavaScript!"; // local variable
alert( message );
}
showMessage(); // Hello, I'm JavaScript!
alert( message ); // <-- Error! The variable is local to the function
userName. The outer one is ignored.let userName = 'John';
function showMessage() {
let userName = "Bob"; // declare a local variable
let message = 'Hello, ' + userName; // Bob
alert(message);
}
// the function will create and use its own userName
showMessage();
alert( userName ); // John, unchanged, the function did not access the outer variable
from and text. You can use outside the function.function showMessage(from, text) {
from = '*' + from + '*'; // now it becomes, *Ann*
alert( from + ': ' + text );
}
let from = "Ann";
showMessage(from, "Hello"); // *Ann*: Hello
// the value of "from" is the same, the function modified a local copy
alert( from ); // Ann
function showMessage(from, text = "no text given") {
alert( from + ": " + text );
}
showMessage("Ann"); // Ann: no text given
result above)return or without it returns undefinedfunction sum(a, b) {
return a + b;
}
let result = sum(1, 2);
alert( result ); // 3
// empty return
function doNothing() { /* empty */ }
alert( doNothing() === undefined ); // true
function doNothing() {
return;
}
alert( doNothing() === undefined ); // true
Function starting with:
“get…” – return a value,
“calc…” – calculate something,
“create…” – create something,
“check…” – check something and return a boolean, etc.
showMessage(..) // shows a message
getAge(..) // returns the age (gets it somehow)
calcSum(..) // calculates a sum and returns the result
createForm(..) // creates a form (and usually returns it)
checkPermission(..) // checks a permission, returns true/false
=), this is a Function Expression.function declaration, no need to write a name, called anonymous function.let sayHi = function() { // function expression
alert( "Hello" );
};
sayHi().; is recommended at the end of the statement, it’s not a part of the function syntax.function sayHi() {
alert( "Hello" );
}
alert( sayHi ); // shows the function code
// ------------------------------------
// ------------------------------------
function sayHi() { // (1) create
alert( "Hello" );
}
let func = sayHi; // (2) copy
// let func = sayHi(); // ❌ wrong, remove paranthesis to copy
func(); // Hello // (3) run the copy (it works)!
sayHi(); // Hello // this still works too (why wouldn't it)
let sayHi = function() {
// ...
}; // semicolon at end of expression
function that is passed as an argument to another function.function ask(question, yes, no) {
if (confirm(question)) yes()
else no();
}
function showOk() {
alert( "You agreed." );
}
function showCancel() {
alert( "You canceled the execution." );
}
// usage: functions showOk, showCancel are passed as arguments to ask
ask("Do you agree?", showOk, showCancel);
hoisting| ```js // Function Declaration function sum(a, b) { return a + b; } ``` | ```js // Function Expression let sum = function(a, b) { return a + b; }; ``` |
sayHi("John"); // Hello, John WORKS
function sayHi(name) {
alert( `Hello, ${name}` );
}
// FUNCTION DECLATION CAN WRITE ABOVE OR BELOW CALLER.
| ```js function sayHi() { // (1) create alert( "Hello" ); } let func = sayHi; // (2) copy func(); // Hello // (3) run the copy (it works)! sayHi(); // Hello // this still works too (why wouldn't it) ``` | ```js let sayHi = function() { // (1) create alert( "Hello" ); }; let func = sayHi; // same as beside mention ``` |
| Calling before declaration | |
|---|---|
| ```js sayHi("John"); // Hello, John function sayHi(name) { alert( `Hello, ${name}` ); } ``` | ```js sayHi("John"); // error! let sayHi = function(name) { // (*) no magic any more alert( `Hello, ${name}` ); }; ``` |
return statement.
- Without curly braces: (...args) => expression, function evaluate implicitly returns the result
- With curly braces: (...args) => { return body } but we need an explicit return to return something.| Arrow function | Function Expression |
| ```js let func = (arg1, arg2, ..., argN) => expression; ``` | ```js let func = function(arg1, arg2, ..., argN) { return expression; }; ``` |
let sum = (a, b) => a + b; // single line function
alert( sum(1, 2) ); // 3
// --------------------
// --------------------
let sum = (a, b) => { // the curly brace opens a multiline function
let result = a + b;
return result; // if we use curly braces, then we need an explicit "return"
};
alert( sum(1, 2) ); // 3
let double = n => n * 2;
// roughly the same as: let double = function(n) { return n * 2 }
alert( double(3) ); // 6