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 Description Example
var Used to initialize to value, redeclared and its value can be reassigned. var x= value;
let Similar to var but is block scoped let y= value;
const Used to declare a fixed value that cannot be changed. const z= value;

II. Datatypes

Datatype Description Example
Number Numeric values can be real number or integers. var x= number;
String Series of multiple characters written in quotes. var x= “characters”;
Boolean Has only two values true or false. var x= true/false;
Null Special value that represents that the variable is empty. var x= null;
Undefined Represents a variable which is declared but not assigned any value. let x; / let x= undefined;
Object Complex data type that allows us to store a collection of data. var x= {
    key: “value”;
    key: “value”;
}
Array Stores multiple values of same type in a single variable.

var x =['y1', 'y2','y3','y4'];

y: any datatype

Function Functions are objects that can be called to execute a block of code.

function x(arguments){

    block of code

}

III. Operators

Operators Description Symbols
Arithmetic Used to perform basic arithmetic operations on variables(operands). + Addition j
- Subtraction
* Multiplication
/ Division j / 3.13 % Modulus (division remainder)
++ Increment
-- Decrement
Comparison Comparison operator is used to compare two operands. == Is equal to
!= Is not equal to
> Is greater than
< Is less than
>= Is greater than or equal to
<= Is less than or equal to
=== Is equal to (and of the same type)
!== Is not equal to (and of the same type)
Bitwise Used to perform bitwise operations. &, | , ^,~,<<, >>, >>>
Logical

There are three logical operators in javascript.

  • logical AND: When all the operands are true.
  • logical OR: When one or more than one operands are true.
  • logical NOT: Converts true to false.
&& And
|| Or
! Not
Assignment Assignment operators assign values to JavaScript variables. =
+=
-=
*=
/=
%=

IV. Scope

scope Description
function 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.
global 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).
block Block scope restricts the access of a variable outside its scope

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
Function names are case-sensitive.

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()

Or you can use the shorthand form, as follows:

arrayname = []

arrayname[0] = value_1

You 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.

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

Loop Description Syntax
for Loops over a block of with conditions specified in the beginning. for (initialization condition; testing condition;increment/decrement)
{
    statement(s)
}
while Entry control loop which executes after checking the condition. while (boolean condition)
{
    loop statements…
}
do-while Exit Control Loop which executes once before checking the condition.

do
{
    statements..
}

while (condition);

for-in Another version of for loop to provide a simpler way to iterate. for (variableName in Object)
{
    statement(s)
}
break Breaks out from a loop. for (initialization condition; testing condition;increment/decrement)
{
    statement(s)
    if (found) break;
}
continue Sometimes you don't want to entirely exit from a loop but instead wish to skip the
remaining statements just for this iteration of the loop. In such cases, you can use the
continue command
for (initialization condition; testing condition;increment/decrement)
{
    statement(s)
    if (not found) continue;
    statement(s)
}

VIII. Conditionals

There are three types of nonlooping conditionals: the if statement, the switch statement, and the ? operator.

Conditionals Description Syntax
if...else The code within such a statement is executed only if the given expression evaluates to true.
When a condition has not been met, you can execute an alternative by using an else statement.
JavaScript has no elseif statement.
if (Condition)
{
    statement(s)
} else{
    statement(s)
}
switch The switch statement is useful when one variable or the result of an expression can have multiple values
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.
switch (variable)
{
    case value_1:
       statement(s)
       break
    case value_2:
       statement(s)
       break
    default:
       statement(s)
       break
}
The ? Operator The ternary operator (?), combined with the : character, provides a quick way of doing if...else tests.
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.

Variable = Condition ? value if true : value if false


EX: 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.