Introduction to JavaScript
To call JavaScript code, you place it between opening <script> and closing
</script> HTML tags.
There is no trailing semicolon (;) because a newline serves the same purpose as a semicolon in JavaScript.
However, if you wish to have more than one statement on a single line, you do need to place a semicolon after
each command except the last one.
In addition to placing a script within the body of a document, you can put it in the
<head> section, which is
the ideal place if you wish to execute a script when a page loads.
You can include files of JavaScript code either from your website or from anywhere on the internet:
<script type="text/javascript" src="./path/script.js"> </script>
<script src="http://My_Server.dz/script.js"> </script>
I. Variables
- A variable may include only the letters a-z, A-Z, 0-9, the $ symbol, and the underscore (_).
- No other characters, such as spaces or punctuation, are allowed in a variable name.
- The first character of a variable name can be only a-z, A-Z, $, or _ (no numbers).
- Names are case-sensitive. Count, count, and COUNT are all different variables.
- There is no set limit on variable name lengths.
Variable declaration
- var: Used to initialize to value, redeclared and its value can be reassigned.
var age = 55; var Teacher_Name = "Karim"; var isStudent = false; console.log(Teacher_Name + " is " + age + " years old");
- let: Similar to var but is block scoped.
{ let age = 18; let Student_Name = "Amel"; let isStudent = false; console.log("Inside the block: "+Student_Name + " is " + age + " years old"); } console.log("Outside the block: "+Student_Name + " is " + age + " years old");
- const: Used to declare a fixed value that cannot be changed.
const Pi = 3.14; Pi = 3.14159; // This will throw an error
II. Datatypes
-
Number
var WebDev_Grade = 0.000001;
-
String
var Student_Name = "Ahmed"; var Student_Name2 = 'Ahmed';
-
Boolean
var isStudent = true;
-
Null
var x = null; console.log("The value of x is: " + x); // Output: The value of x is: null
-
Undefined
var y; let z = undefined; console.log("The value of y is: " + y); // Output: The value of y is: undefined console.log("The value of z is: " + z); // Output: The value of z is: undefined
-
Object
var Student = { Name: "Ahmed", Age: 20, isStudent: true }; console.log(Student.Name + " is " + Student.Age + " years old");
III. Operators
-
Arithmetic
var x = 5; var y = 2; console.log(x + y); // Addition console.log(x - y); // Subtraction console.log(x * y); // Multiplication console.log(x / y); // Division console.log(x % y); // Modulus console.log(++x); // Increment console.log(x++); // It will print 6, beacuse it will increment after printing console.log(--x); // Decrement console.log(x--); // It will print 6, beacuse it will decrement after printing
-
Comparison
var x = 5; var x2 = "5"; var y = 2; console.log("Is x equal to y: ", x == y); // Equal to console.log("Is x equal to x2: ", x == x2); // Equal to console.log("x is not equal to y: ", x != y); // Not equal to console.log("Is x greater than y: ", x > y); // Greater than console.log("Is x less than y: ", x < y); // Less than console.log("Is x greater than or equal to y: ", x >= y); // Greater than or equal to console.log("Is x less than or equal to y: ", x <= y); // Less than or equal to console.log("Is x equal to (and of the same type) y: ", x === y); // Equal to (and of the same type) console.log("Is x equal to (and of the same type) x2: ", x === x2); // Equal to (and of the same type) console.log("x is not equal to (and of the same type) y: ", x !== y); // Not equal to (and of the same type) console.log("x is not equal to (and of the same type) x2: ", x !== x2); // Not equal to (and of the same type)
-
Bitwise
var x = 5; // 101 var y = 2; // 010 var z = -1; // 111 console.log("x Bitwise AND y: ", x & y); // It will return 0 console.log("x Bitwise OR y: ", x | y); // It will return 7 console.log("x Bitwise XOR y: ", x ^ y); // It will return 7 console.log("Bitwise NOT x: ", ~x); // It will return -6 console.log("Bitwise Left Shift x by 1: ", x << 1); // It will return 10 console.log("Bitwise Right Shift x by 1: ", x >> 1); // It will return 2 console.log("Bitwise Right Shift x with Zero", z >>> 1); // It will return 2147483647
-
Logical
var x = true; var y = false; console.log("x AND y: ", x && y); // And console.log("x OR y: ", x || y); // Or console.log("NOT x: ", !x); // Not
-
Assignment
var x = 5; x += 2; // x = x + 2 console.log(x); // It will print 7 x -= 2; // x = x - 2 console.log(x); // It will print 5 x *= 2; // x = x * 2 console.log(x); // It will print 10 x /= 2; // x = x / 2 console.log(x); // It will print 5 x %= 2; // x = x % 2 console.log(x); // It will print 1
IV. Scope
-
Global Scope
The variables in global scope can be accessed from anywhere in the program.
Global variables are ones defined outside of any functions (or defined within functions but without the var keyword).var x = 5; let y = 10; function myFunction() { console.log(x); console.log(y); // global scope variable y = 7; } myFunction(); // It will print 5 console.log(y); // It will print 7
-
Local Scope
Variables declared inside a function is inside the function scope also known as local scope.
Parameters passed to a function automatically have local scope.
To define a local variable that has scope only within the current function, and has not been passed as a parameter, use the var keyword.function myFunction() { var x = 5; console.log(x); } myFunction(); // It will print 5 console.log(x); // It will throw an error
-
Block Scope
Block scope restricts the access of a variable outside its scope
{ let x = 5; var y = 10; console.log(x); console.log(y); } console.log(y); // It will print 10 console.log(x); // It will throw an error
With the let keyword you cannot redeclare a variable once you have done so with let.
let keyword is either globally or block scoped, and variables are not initialized.
Any variable assigned using let has scope either within the entire document if declared outside of any block,
or, if declared within a block bounded by {} (which includes functions), its scope is limited to that block
(and any nested sub-blocks).
If you use the const keyword to declare the variable and assign its value, any attempt to change the value
later will be disallowed.
const declarations are also block scoped (within {} sections and any sub-blocks)
In summary: var has global or function scope, and let and const have global or block scope. Both var and let can be declared without being initialized, while const must be initialized during declaration. The var keyword can be reused to re-declare a var variable, but let and const cannot. Finally, const can neither be redeclared nor reassigned.
V. Functions
The general syntax for a function is:
function function_name([parameter [, ...]]) { statements }
- A definition starts with the word function.
- A name follows that must start with a letter or underscore, followed by any number of letters, digits, dollar signs, or underscores.
- The parentheses are required.
- One or more parameters, separated by commas, are optional
The opening curly brace starts the statements that will execute when you call the function; a matching curly brace must close it. These statements may include one or more return statements, which force the function to cease execution and return to the calling code. If a value is attached to the return statement, the calling code can retrieve it.
VI. Arrays
To create a new array, use the following syntax:
// arrayname = new Array() Teachers = new Array("Karim", "Kamel", "Ahmed", "Khaled"); console.log(Teachers[2]); // It will print AhmedOr you can use the shorthand form, as follows:
Modules = []; Modules[0] = "Web Development"; Modules[1] = "Mobile Development"; Modules[2] = "Data Science"; Modules[3] = "AI"; Modules[4] = "Cyber Security"; console.log(Modules[1]); // It will print Mobile DevelopmentYou can also create an array together with some initial elements by using the Array keyword, like this:
Team_G_12_1 = Array("Omar", "Kamel", "Manel", "Nour", "Hana", "Sami", "Sara");There is nothing stopping you from adding more elements afterward as well.
Arrays can hold any type of data, including numbers, strings, and objects. We can even have arrays with multiple types of data.
Popular methods for arrays
Method | Description |
push() | Adds a new element at the very end of an array. |
pop() | Removes the last element of an array. |
concat() | Joins various arrays into a single array. |
shift() | Removes the first element of an array |
unShift() | Adds new elements at the beginning of the array |
reverse() | Reverses the order of the elements in an array. |
slice() | Pulls a copy of a part of an array into a new array. |
splice() | Adds elements in a particular way and position. |
toString() | Converts the array elements into strings. |
valueOf() | Returns the primitive value of the given object. |
indexOf() | Returns the first index at which a given element is found. |
lastIndexOf() | Returns the final index at which a given element appears. |
join() | Combines elements of an array into one single string and then returns it |
sort() | Sorts the array elements based on some condition. |
VII. Loops
For loop
for (let i = 0; i < 4; i++) { console.log(Teachers[i]); }
While loop
while (students.length > 0) { console.log(students.pop()); }
Do...While loop
i = 0; do { console.log(Modules[i]); i++; } while (i < Modules.length);
For...in
for (let index in Teachers) { console.log(Teachers[index]); }
Break
for (let index in Modules) { if (index == 2) break; console.log(Modules[index]); }
Continue
for (let index in Modules) { if (index == 2) continue; console.log(Modules[index]); }
VIII. Conditionals
There are three types of nonlooping conditionals: the if statement, the switch statement, and the ? operator.
if...else
When a condition has not been met, you can execute an alternative by using an else statement.
JavaScript has no elseif statement.
var Grade = 5; if (Grade >= 10) { console.log("You passed the exam"); } else { console.log("You failed the exam"); }
switch
and you want to perform a different function for each value.
The break command allows your code to break out of the switch statement once a condition has been
satisfied.
When no condition is satisfied, you can specify a default action for a switch statement
by using the default keyword.
var day = 3; switch (day) { case 1: console.log("Sunday"); break; case 2: console.log("Monday"); break; case 3: console.log("Tuesday"); break; case 4: console.log("Wednesday"); break; case 5: console.log("Thursday"); break; case 6: console.log("Friday"); break; case 7: console.log("Saturday"); break; default: console.log("Invalid Day"); }
The ? Operator
With it you can write an expression to evaluate and then follow it with a ? symbol and the code to execute if the expression is true.
After that, place a : and the code to execute if the expression evaluates to false.
var Pass = (Exam >= 10) ? true : false;
IX. Strings
Methods | Description |
concat() | Used for concatenating multiple strings into a single string. |
match() | Used for finding matche of a string against a provided pattern. |
replace() | Used for finding and replacing a given text in string. |
substr() | Used to extract length characters from a given string. |
slice() | Used for extracting an area of the string and returs it |
lastIndexOf() | Used to return the index (position) of the last occurrence of a specified value. |
charAt() | Used for returning the character at a particular index of a string |
valueOf() | Used for returning the primitive value of a string object. |
split() | Used for splitting a string object into an array of strings. |
toUpperCase() | Used for converting strings to upper case. |
toLoweCase() | Used for converting strings to lower case. |
X. Numbers and maths
Method | Description |
max(x,y,z…n) | Returns the highest-valued number |
min(x,y,z…n) | Returns the lowest-valued number |
exp(x) | Returns x's exponential value. |
log(x) | Returns the natural logarithm (base E) of x. |
sqrt(x) | Returns x's square root value. |
pow(x,y) | Returns the value of x to the power of y |
round(x) | Rounds the value of x to the nearest integer |
sin(x) | Finds the sine value of x(x is in radians). |
tan(x) | Finds the angle's(x) tangent value. |