1 - Basics of JavaScript
1 - Basics of JavaScript
1
Course: Foundations of Web
Development
Lecture On:text
Edit Master Basics
stylesof
JavaScript
2
Introduction to JavaScript
• JavaScript (JS) is the programming language of web development. It was initially used to ‘make web pages
alive’.
• Unlike Java, scripts do not require any compilation to run. JS can execute on a browser, a server and any
device that has a ‘JavaScript Engine’.
• JS does not provide low-level access to memory or CPU, which is why it is a ‘safe’ programming language.
1. Adding or modifying HTML content on a page, including, but not restricted to, showing/hiding elements
as well as changing the size, style and HTML attributes
2. Reacting to user actions such as hovering, mouse clicks, key presses, etc.
3. Sending requests to remote servers over the network and saving the data on the client side.
4
Introduction to JavaScript
Where to place scripts in HTML document
JavaScript
Internal External
• JavaScript (JS) can be placed either internally in an HTML file using the <script> tag, where you can write all the scripts
inside the <script> tag, or externally in a JavaScript file (that ends with a ‘.js’ extension), which can be added as a
source in the <script> tag.
• The <script> tag can be placed either in the <head> or in the <body> part of the HTML document.
• However, because JS is a render blocker, it is preferable to call these scripts in the <body> tag after all the HTML
elements are rendered.
5
Introduction to JavaScript
Where to place scripts in JavaScript
index.html index.js
<html> function onClick() {
<head> alert(“Clicked”);
<script> }
function onClick() { alert(“Clicked”); }
</script>
</head> <html>
<body> <head>
<button onclick=“onClick()”>Click here.</button> <script src=“index.js”></script>
</body> </head>
</html> <body>
<button onclick=“onClick()”>Click
here.</button>
</body>
</html>
index.html 6
Click
Poll 1 to
(15add
Sec)Title
Which of the following is the syntactically INCORRECT method of including JavaScript
into an HTML code?
23/05/19 7 7 7
Click
Poll 1 to add Title
(Answer)
Which of the following is the syntactically INCORRECT method of including JavaScript
into an HTML code?
23/05/19 8 8 8
Introduction to JavaScript
JavaScript Output
JavaScript (JS) can display data in the following different ways. We shall start looking at the first method which
is:
Using console.log(): For debugging purposes, you can use console.log() to log the JS code in the browser’s
developer tools.
console.log(‘Hello World.’);
9
Introduction to JavaScript
JavaScript Output
JavaScript (JS) can display data in the following four different ways:
1. Writing into an HTML element: Using document.getElementById(id), you can fetch an element with an id,
and then, using innerHTML, you can write into an HTML element.
document.getElementById(‘text1’).innerHTML = “This is a paragraph” ;
2. Writing into the HTML output: Using document.write(), you can write into the document, i.e., the web page
directly. Please note that when you use document.write(), the entire HTML will get deleted and replaced by
the content inside the parentheses of document.write().
document.write(‘Hello World.’);
3. Using window.alert(): Using window.alert(), you can display data in an alert box on the web page.
window.alert(‘Hello World.’);
4. Using console.log(): For debugging purposes, you can use console.log() to log the JS code in the
browser’s developer tools.
console.log(‘Hello World.’);
10
function clickMe() {
JavaScript Syntax }
alert(“I am clicked!”);
• JavaScript (JS) programs are a list of programming instructions called statements that are executed by web
browsers.
• JS statements consist of values, operators, expressions, keywords and comments. They are executed in a
waterfall fashion, that is, one by one, in the order in which they are written.
12
JavaScript Syntax
JavaScript Syntax
• Generally, a JavaScript (JS) code consists of statements with variables that store values or expressions.
var x, y; //Declaring variables
var num1 = 24; //Assigning values to variable
var num2 = 30; //Assigning values to variable
var total = num1 + num2; //Computing expressions and storing result in variable
• In a programming language, variables are used to store data values. In JS, variables are declared using the var
keyword. An equal sign (‘=’) is used to assign value to the variables.
• JS values can be strings, numbers, arrays, objects, booleans or expressions. String values need to be written within
single or double quotes, for example, ‘John Doe’ or “John Doe”, and number values should not be written within
quotes, for example, 2 or 200.45.
13
JavaScript Syntax
JavaScript Syntax
• For single-line JS comments, you can use “//”, and for multiline comments, you can use “/* */”.
14
JavaScript Syntax
JavaScript Terminology
• JavaScript (JS) programs are a list of programming instructions called statements that are executed by web
browsers.
• JS statements consist of values, operators, expressions, keywords and comments. They are executed in a
waterfall fashion, that is, one by one, in the order in which they are written.
• JS statements end with a semicolon (‘;’). Semicolons essentially separate JS statements. It is not mandatory
to add a semicolon, but it is highly recommended. Using semicolons, you can add multiple JS statements in
one line. For example,
15
JavaScript Syntax
JavaScript Terminology
• JS ignores multiple spaces. However, it is recommended to add white spaces to your code to make it more
readable. For example,
var name = “John”;
..
• A best practice is to avoid having more than 80 characters in one line for better readability. The best place to
break a JS code to a new line is immediately after the operator.
16
JavaScript Syntax
JavaScript Variables: Identifiers and Data Types
• JavaScript (JS) variables are containers for storing data values. In earlier examples, you learnt that variables can
store values and expressions.
• All JS variables must be identified with a unique name called identifier. The rules for writing an identifier name
are as follows:
1. Names can contain letters, digits, the dollar sign (‘$’) and the underscore sign (‘_’).
2. Names should always begin with a letter.
3. JavaScript is case-sensitive, i.e., name and Name are different variables.
4. Reserved JS words cannot be used for an identifier.
5. The best practice is to not keep a name, such as x, y, z, that does not indicate the meaning or
significance of that variable. The identifier name should signify the meaning of the variable; for
example, name and age.
• In JS, you can assign a value to the variable using the ‘=’ operator.
17
JavaScript Syntax
JavaScript Variables: Declaring Variables
Creating a variable in JavaScript (JS) is called declaring a variable. You can declare a JS variable using the var
keyword.
var name;
When a variable is declared as shown in the example given above, its value is undefined. Use the assignment
operator to assign a value to the variable. If the variable is already declared, then you need not use the keyword var
again.
name = “John Doe”;
18
JavaScript Syntax
Primitive Data Types
• In JavaScript (JS), primitive data types refer to the data types that are used to store specific data of the
same type, which means that they are not an object and do not have methods.
• The five primitive data types are as follows: String, Number, Boolean, undefined and null.
• All primitive values are immutable, i.e., they cannot be altered. You can conveniently assign a new value
to a variable storing a primitive value, but you cannot change the value of a primitive data type.
true
123 “A*” false
null
Number
String Boolean undefined
19
“The quick
Strings brown fox
jumps over
the lazy dog.”
Full Stack Software Development 20
JavaScript Syntax
Primitive Data Types: Introduction to Strings
• JavaScript (JS) strings are used for storing and manipulating text.
var firstName = “John”;
• A JS string contains zero or more characters inside a string.
var lastName = ‘Doe’;
var x = “The nickname “Red Devils” is given to the players playing for Manchester United FC.”;
In the example given above, JS engine will be confused when it encounters the second double quote before
the word Red. Therefore, the string will be clipped to “The nickname”. To avoid such a scenario, you can
wrap the entire sentence in single quotes or use an escape character.
The backlash (\”) or (\’) escape character converts any special character into string characters.
\‘ ‘
var x = “The nickname \“Red Devils\” is given to
\“ “ the players playing for Manchester United FC.”;
\\ \ 21
JavaScript Syntax
Primitive Data Types: String Methods
indexOf() and lastIndexOf(): indexOf() returns the position of the first occurrence of text in a string, whereas
lastIndexOf() returns the last position of the occurrence of text in a string. You can even add a second
parameter to signify the starting position for the search. If the text is not found in the string, then the value
returned is -1.
var str = “I have to go to New York.”;
console.log(str.indexOf(“to”)); //7
console.log(str.lastIndexOf(“to”)); //13
console.log(str.indexOf(“e”, 4)); //5
console.log(str.indexOf(“Mumbai”)); //-1
JavaScript Syntax
Primitive Data Types: String Methods
slice(start, end):
• It extracts part of the string and returns the extracted part in a new string without modifying the original string.
• The method takes two parameters, the start position and the end position;
• For instance, in the example given below, the start position is given as 7, and the end position is given as 12. So,
the method will take the values from the positions 7 to 12.
If the second parameter is not given, then the method will slice out until the end of the string.
23
JavaScript Syntax
Primitive Data Types: String Methods
substring(start, end): It is similar to slice(). The only difference is that substring() does not accept negative
indices. If you omit the second parameter, then it will extract the rest of the string.
var str = “I have to go to New York.”; console.log(str.substring(7, 12)); //to go
substr(start, length):
• substr() is also similar to slice() and substring(). The difference is that the second parameter is the
length of the extracted part.
• It accepts a negative number in the first parameter, and that will start counting from behind.
• If the second parameter is not specified, then it will extract the remaining part of the string.
24
JavaScript Syntax
Primitive Data Types: String Methods
replace(text1, text2):
• The replace() method finds the first parameter in a string and replaces it with a second string.
• It does not change the string it is called on but returns a new string.
var str = “I have to go to New York City in the New York state.”;
console.log(str.replace(“New York”, “Mumbai”)); //I have to go to Mumbai City in the New York state.
console.log(str.replace(“NEW YORK”, “Mumbai”)); //
console.log(str.replace(“/NEW YORK/i”, “Mumbai”)); //I have to go to Mumbai City in the New York state.
console.log(str.replace(“/New York/g”, “Mumbai”)); //I have to go to Mumbai City in the Mumbai state.
25
JavaScript Syntax
Primitive Data Types: String Methods
toUpperCase() and toLowerCase(): The toUpperCase() method converts a string to the upper case, and the
toLowerCase() method converts a string to the lower case.
concat(): The concat() method joins two or more strings. It is the same as the ‘+’ operator.
trim(): The trim() method removes white spaces from the string.
var str = “ Hello. ”; console.log(str.trim()); //Hello
26
JavaScript Syntax
Primitive Data Types: String Methods
charAt(position): The charAt() method returns the character at a specified index (position) in a string. The first
position is always 0.
[position]: Using [], you can access the character at that position.
27
Numbers
var num1 = 5, num2 = 4; var num1 = “5”, num2 = var num1 = “5”, num2 =
var sum = sum1 + sum2; //9 “4”; “4”;
var sum = sum1 + sum2; var sum = num1 * num2;
//54 //20
var num1 = “5”, num2 = “4”;
var num1 = 5, num2 = “4”;
var sum = “Result: ” + x +
var sum = 1 + x + y; //64
y; //Result54
29
JavaScript Syntax
Primitive Data Types: NaN and Infinity
• NaN is a JavaScript-reserved keyword for notifying that a number is not a legal number. If you try to perform
arithmetic operations with a non-numeric string, the result will be NaN.
var x = 4;
var y = “Apple”;
var z = x / y; //NaN
• Infinity or –Infinity is the value returned when the calculation results in a number more than the largest possible
number. Dividing a positive number by zero results in infinity. Dividing a negative number by 0 results in -Infinity.
var x = 4;
var y = 0;
var z = x / y; //Infinity
30
JavaScript Syntax
Primitive Data Types: Number Methods
• Before you take a look at number methods, typeof is an operator that helps in identifying the data type of a value.
toString(): The toString() method returns a number as a string. It can change any number, even if the method is inside
a variable or is an expression.
var x = 200;
console.log(typeof x.toString(), x.toString()); //string 200
console.log(typeof (123).toString(), (123).toString()); //string 123
console.log(typeof (123+100).toString(), (123+100).toString()); //string 223
toFixed(): The toFixed() method returns the number as a string with a specified number of decimals.
var x = 10.639;
console.log(x.toFixed(0)); //11
console.log(x.toFixed(1)); //10.6
console.log(x.toFixed(2)); //10.64
31
JavaScript Syntax
Primitive Data Types: Number Methods
Number(): The Number() method returns a number. It converts numeric strings into numbers, dates into milliseconds
since 1 January 1970, and true/false as 1/0 respectively.
parseInt(): The parseInt() method parses a string and returns a whole number. The parsed number is returned till the
point where the first non-whitespace character cannot be converted to a number.
parseInt(“10”); //10
parseInt(“10.33”); //10
parseInt(“10 20 30”); //10
parseInt(“10 years”); //10
parseFloat(): The parseFloat() method parses a string and returns a floating-point number.
parseFloat(“10”); //10
parseFloat(“10.33”); //10.33
parseFloat(“10 years”); //10
32
var firstNum = 1;
var secondNum = 2;
var newNum = 1;
Boolean
var booleanVariable1 = true;
var booleanVariable2 = false;
var y = null;
• You can deliberately assign the value undefined to any variable in JS.
• However, an empty value is not undefined. var firstName = “”; is not undefined, and it has some value, which
is empty string.
• null is a type in itself although typeof null is object. In JS, null is nothing. It is supposed to be something that does not
exist.
35
Operators /-
*
Full Stack Software Development 36
JavaScript Operators
Different Types of Operators
There are different types of operators: you can find the entire list here.
We would be covering five types of operators: arithmetic (to perform arithmetic operations on numbers), assignment (to
assign values to JavaScript variables), comparison (to compare values), logical (to determine the logical relationship
between variables/values) and type (to identify the datatype of variables).
Operators
37
JavaScript Operators
Arithmetic Operators
Arithmetic operators help in performing arithmetic operations on JavaScript (JS) numbers. Arithmetic operations can be
performed between values and variables, and they can also include expressions.
var x = 5, y = 2;
console.log(x + y); //7
console.log(x - y); //3
console.log(x * y); //10
console.log(x / y); //2.5
console.log(x % y); //1 /* % is modulus operator which calculates the remainder of division
x++;
console.log(x); //6
x--;
console.log(x); //5
console.log(x ** y); //25 /* ** is exponential operator */
console.log(x ** y/x); //5 /* ** is has more precedence as compared to / */
Operator precedence:
parentheses > division > multiplication > addition > subtraction
38
JavaScript Operators
Assignment Operators
Compound assignment operators are shorthand operators to assign values to JavaScript variables after doing some
operation.
39
JavaScript Operators
Comparison Operators
Comparison operators are used in logical statements to determine equality or difference between variables or values.
The comparison operators are as follows:
1. > and >=: These operators are used to compare two
numbers and determine which number is greater. >= var x = 2; //Assigns value 2 to x
console.log(x == 2); //true
also includes the number to the right of the operator. console.log(x == 8); //false
2. < and <=: These operators are used to compare two console.log(x == “2”); //true
numbers and determine which number is smaller. <= console.log(x === 2); //true
console.log(x === “2”); //false
also includes the number to the right of the operator.
3. ==: This operator is used to check whether two console.log(x != 5); //true
numbers are equal. Therefore, if you compare a console.log(x != 2); //false
number with a numeric string where both have the console.log(x !== “2”); //true
same value, then it will return true. console.log(x > 0); //true
4. ===: This operator is a stricter check for equality. It console.log(x > 2); //false
also checks for types of the variables. Therefore, if you console.log(x >= 2); //true
compare a number with a numeric string, then it will console.log(x < 5); //true
console.log(x < 2); //false
return false. console.log(x <= 2); //true
5. !=: This operator is used to check whether two
numbers are not equal.
6. !==: This operator is a stricter check for non-equality.
Like ===, it also checks for types of the variables.
40
JavaScript Operators
Logical Operators
Logical operators are used in logical statements to determine the logic between two or more expressions, values or
variables. The logical operators are as follows:
var x = 2, y = 6;
console.log(x > 0 && y < 10); //true
1. &&: This operator returns true only when all the console.log(x > 5 && y < 10); //false
expressions are true.
console.log(x > 0 || y < 10); //true
console.log(x > 5 || y < 10); //true
2. ||: This operator returns true only if either of the console.log(x > 5 && y < 4); //false
expressions is true.
console.log(!(x == 5)); //true
console.log(!(x >= 5)); //true
3. !: This operator returns true for false statements and
false for true statements.
41
JavaScript Operators
Type Operators
42
JavaScript Operators
Type Conversion
In JavaScript (JS), you can convert variables from one type to another using JavaScript functions. Also, sometimes JS itself converts
the datatype of the variables.
Converting numbers to strings: You can use the global method String() or the toString() method. Even when you use
number methods, such as the toFixed() method or the toPrecision() method, the value gets converted to a string.
var x = 2.56;
console.log(typeof String(x)); //string
console.log(typeof x.toString()); //string
console.log(typeof x.toFixed(1)); //string
Converting strings and booleans to numbers: Numeric strings can be converted to numbers. On the other hand, the
conversion of non-numeric strings to numbers will result in NaN. You can use the global method Number() or use a unary
operator, such as +, before a string to convert it to a number. Also, using methods, such as parseInt() and parseFloat()
methods, will return numbers. For boolean, the Number() method can convert a boolean to a number.
43
JavaScript Operators
Automatic Type Conversion
• When JavaScript tries to operate on a “wrong” data type, it automatically converts it to a “right” data type.
• When you try to output an object or a variable, the toString() function is automatically called, and the object/variable
is converted to a string.
44
Type Coercion
When you add a string and numbers, if the string is declared first, then the remaining values (even if they are
numbers) will be considered to be strings.
However, if numbers are declared first, then the remaining values are considered to be numbers until they reach
a string
var x = 5 + 2 + “3”; //73
var y = 2 + 3 + “HTML”; //5HTML
46
if ()
JavaScript
Conditions
else ()
• Conditional statements help JavaScript perform different actions based on certain given conditions.
• There are two types of conditional statements in JS: if...else and switch().
if () switch ()
case 1:
else ()
case 2:
48
JavaScript Conditions
If…else
• The first variant is the if conditional statement. It checks whether a specified condition in a parameter is true or false.
If it is true, then it executes the code corresponding to the condition, and if it is false, it does not execute the condition
inside the block.
• Another variant is the if…else conditional statement. If the condition in the if statement is true, then the code will
execute that condition. However, if it is false, then it will execute the else block.
var x = “Hello”;
var x = 3;
var x = 2; if(x % 2 == 0) {
if(x % 2 == 0) { console.log(“The number is even”);
if(x % 2 == 0) { console.log(“The number is even”); } else if (x % 2 == 1){
console.log(“The number is even”); } else { console.log(“The number is odd”);
} console.log(“The number is odd”); } else {
//The number is even } console.log(“x is not a number”);
//The number is odd }
//x is not a number
49
JavaScript Conditions
Switch
The switch statement can be used to perform different actions based on different conditions. In the switch parentheses,
an expression needs to be added. The answer to that expression evaluation will be one of the cases inside the switch
statement. If none of the cases match, then the code should go to default. The switch statement is like a waterfall: If the
first case matches the value, then it executes the code written inside the first case but it will go to all the cases and
execute statements in them. To avoid this, every case should end with a break. The break keyword stops the execution
at that point and comes out of the switch.
var x = 3;
switch(x - 2) {
case 0:
console.log(“The answer is zero”);
break;
case 1:
console.log(“The answer is one”);
break;
case 2:
console.log(“The answer is two”);
break;
default:
console.log(“x is not a number”);
}
// The answer is one
50
JavaScript
Looping
• In JavaScript, there are three different methods for looping: for(), while(), and do…while().
while (condition) { do {
for (condition) {
} } } while (condition)
52
JavaScript Looping
The for loop
Let’s assume that you have an array and you want to print every element in the array on a different line. You would have
to run the same printing statement again and again, with different indices of the array.
In this case, it was a small array of four elements. However, if you have an array of 100 elements, then the process
becomes tedious. This is where for loop comes into the picture.
The syntax of a for loop has three statements: statement1, used for initialising variables (it is executed before the
execution of the code block); statement2, which is for condition (it defines the condition for executing the code block);
and statement3, which is for incrementing/decrementing the value initialised in statement1 (it is executed every time
the code block is executed).
for(initialization; condition; updation) {
//code block to execute
}
53
JavaScript Looping
The for loop
for(var i = 0; i < students.length; i++) { • Then, the statement in the code block is executed,
where students[i], which will be students[0] as i = 0,
var text += students[i] + "\n"; will be added to text. Hence, “Rajesh” is appended to
text.
The while loop loops through a block of code as long as the specified condition holds true.
while(condition) {
//code block to execute
}
In simple words, the code block will keep executing as long as the condition mentioned in the parentheses does not
turn false. As shown in the example given below, the code will keep adding value to the text as long as the value of i
remains below 10. An important point to note here is that if the value of i is never incremented, then the loop will keep
executing an infinite number of times, which will crash your browser. So, it is important to ensure that there is always
an increment/decrement of value.
var i = 0, text=””;
while(i < 10) {
text += “The number is ” + i + "\n";
i++;
}
console.log(text);
55
JavaScript Looping
The do…while loop
The do…while loop is similar to the while loop. In the while loop, if the condition is not met, then the code block will not
be executed at all. However, in the do…while loop, the code block will be executed once, and then the condition will be
checked. If the condition is true, then the code block will be executed repeatedly until the condition becomes false.
do {
//code block to execute
}
while(condition);
In the first example given below, the condition is false. However, the code will be executed once, and outputting text
will give “The number is 0”. In the second example, as the condition is true, the code block will be executed until the
condition becomes false. As with the while loop, if the variable is not incremented/decremented, then the browser will
crash because of infinite loop.
• It could be a
○ SyntaxError (for instance, when the starting quote is double quotes but the ending quote is a single
quote, such as “Hello’),
○ TypeError (for instance, when you try to apply a string method to a number.
○ ReferenceError (for instance, when you try to use a variable in an expression without it being declared).
○ RangeError (for instance, when you try to use a number that is outside the range of legal values).
○ URIError (for instance, when unknown characters are used in the URI function).
• If these errors are not handled, then the application might crash, and users will see a blank page or an ugly error
page on their screens.
• On the other hand, if these errors are caught during execution, then they could be handled and redirected as an alert
box, or a custom error page, without the application crashing.
• These errors can be handled using try, catch, throw and finally.
58
JavaScript Error Handling
try, catch, throw and finally
The try statement allows you to test a code block for errors. The catch statement enables you to handle the errors
caught in the try statement. The throw statement allows you to create custom errors. The finally statement executes
the code after try and catch statements regardless of whether an error is caught or not.
try { try {
//Block of code to catch errors alert(“Hello’);
} catch(error) { } catch(error) {
//Block of code to handle caught errors console.log(error);
} } //Uncaught SyntaxError: Invalid or unexpected token
try {
var x = 5;
if(x%2 !== 0)
throw “Not an even number”;
} catch(error) {
console.log(error);
} finally {
console.log(“The code is finally over”);
}
// Not an even number
// The code is finally over
59
Arrays 1 2 3 4 5 6
• However, if you have a list of students and need to loop through it, then, instead of having different variables for
each student, you will need one variable that stores the data of all the students.
• An array can store many values under a single name, and an individual value can be accessed by its position,
which is called an index. The indexing starts from 0. So, the first position is 0, the second position is 1, and so on.
61
JavaScript Syntax
Array Creation, Access and Changing Elements
To access an element in an array, you can call it using its position called index. The first index is 0, the second index
is 1, and so on.
console.log(students[0]); //John
console.log(students[3]); //Sheldon
You can change an element in an array by calling the index and then supplying it with a new value.
students[0] = “Chandler”;
console.log(students); //[Chandler,Dave,Rajesh,Sheldon,Leonard,Howard,Joey]
62
JavaScript Syntax
Array properties and methods
The length of the array can be measured using the length property. You can also access the last element of the
array using this property.
To add new elements to an array, you can use push() method or the length property. However, you should not
add elements whose index is much higher than the length of the array, as that will create holes in the array.
students.push(“Ross”);
console.log(students); //[John,Dave,Rajesh,Sheldon,Leonard,Howard,Joey,Ross]
students[students.length] = “William”;
console.log(students); //[John,Dave,Rajesh,Sheldon,Leonard,Howard,Joey,Ross,William]
students[12] = “Barney”;
console.log(students);
//[John,Dave,Rajesh,Sheldon,Leonard,Howard,Joey,Ross,William,undefined,undefined,undefined,Barney]
63
JavaScript Syntax
Array properties and methods
Use the pop() method to remove (pop out) the last element in an array. Logging its value in the console will display
the removed element.
console.log(students.pop()); // Joey
console.log(students); //[John,Dave,Rajesh,Sheldon,Leonard,Howard]
An array can be converted to a string using either the toString() method or the join() method. In the join() method, you
can specify a separator.
var students = [ “John”, “Dave”, “Rajesh”, “Sheldon”, “Leonard”, “Howard”, “Joey” ];
console.log(students.toString()); //John,Dave,Rajesh,Sheldon,Leonard,Howard,Joey
console.log(students.join(“ / ”)); //Joey / Dave / Rajesh / Sheldon / Leonard / Howard / Joey
Use the delete method to delete an element from an array. This will replace that value with undefined.
delete students[0];
console.log(students); // [empty,Dave,Rajesh,Sheldon,Leonard,Howard]
console.log(students[0]); //undefined
64
JavaScript Syntax
Array Properties and Methods
An array can be shifted using the shift() and unshift() methods. The shift() method removes the first element from an
array and shifts all other elements to the left side with a lower index. Outputting the value of the shift() method will show
the removed element.
On the other hand, the unshift() method adds a new element to the beginning of an array and moves all other elements
to the right side with a higher index.
var students = [“Rajesh”, “Sheldon”, “Leonard”, “Howard”];
console.log(students.shift()); // Rajesh
console.log(students); // [Sheldon,Leonard,Howard]
console.log(students.unshift(“Stuart”)); //4
console.log(students); // [Stuart,Sheldon,Leonard,Howard]
You can merge two or more arrays using the concat() method. This method does not change the original arrays but
returns a new array. The concat() method can take any number of arrays as arguments.
var arr1 = [“BMW”, “Audi”, “Mercedes”], arr2 = [“Honda”, “Hyundai”], arr3 = [“Tata”];
var cars = arr1.concat(arr2, arr3); // [BMW,Audi,Mercedes,Honda,Hyundai,Tata]
65
JavaScript Syntax
Array Properties and Methods
The splice() method allows you to add new items to an array or remove/replace existing items in an array. The first
parameter in the splice() method defines the position where new elements need to be added, the second parameter defines
how many elements need to be removed, and the remaining parameters define the new elements to be added. If only the
first two parameters are specified, then the elements from an array without converting their positions to undefined are
removed. Outputting the value of the splice() method will return the removed elements.
The slice() method slices a piece of an array into a new array. If only one argument in the parameters is specified, then it
slices the array from that position to the end of the array. If two parameters are included, then it slices the array from the
position specified by the first argument to the position specified by the second argument. However, this method does not
include the position specified by the second argument. Note that the original array is not modified.
turnLeft()
company_name
JavaScript Objects
color applyBrake()
weight
All cars have the same properties, but their values differ. Similarly, all cars have the same methods, but they
are performed at different times.
var car = { name: “Mercedes”, model: “C200”, color: “white”, weight: 500 };
Objects are variables that can have multiple values. They are denoted by {}. Objects can contain multiple
properties, and every property must be in a key: value pair.
68
JavaScript Objects
Object methods
var person = {
firstName: “John”,
lastName: “Doe”,
age: 27,
getFullName: function() {
return this.firstName + “ ” + this.lastName;
}
};
• JavaScript (JS) objects can also have methods. For instance, the getFullName property is a method inside
the object that returns the full name by concatenating the first name and the last name inside the object.
• In programming, the this keyword refers to the owner of a property. In the case given above, the property
fullName is owned by the object person. Therefore, this is equal to a person object.
• Therefore, this.firstName will give the output John, whereas this.lastName will give the output Doe.
69
JavaScript Objects
Accessing an object
An object can have another object inside it, which is JavaScript (JS) objects can be accessed in two
called a nested object. In the example given below, ways: bracket notation and dot notation.
address is another object nested inside the object
person.
70
JavaScript Objects
Accessing Objects
You can also loop through the different properties of the objects using the for...in loop.
71
JavaScript Objects
Adding and deleting properties of an object
• To add a property to an existing object, you simply need to declare it using the standard bracket or dot notation
and then assign a value to it.
• Similarly, to delete an object’s property, you can use the delete keyword.
var person = {
firstName: “John”,
lastName: “Doe”,
age: 27,
};
person[“nationality”] = “British”;
person.eyeColor = “blue”;
console.log(person.nationality); //British
delete person.age;
console.log(person); // {firstName: "John", lastName: "Doe"}
72
JavaScript Objects
Looping over an object
var person = {
firstName: “John”,
lastName: “Doe”,
age: 27,
};
var i,details="";
for (i in person) {
details += person[i] + " ";
}
// "John Doe 27 "
73
JavaScript Objects
Pass by Reference
In JavaScript, objects are passed as reference and not as values (i.e., not copied). Two objects that point towards each other will
always remain identical, and changes in one object will automatically reflect in the other.
Note that this holds true only for user-defined types (objects & arrays) and not primitive data types such as strings or
numbers.
74
JavaScript Functions
• In simple terms, JavaScript (JS) function is a block of code designed to perform a specific task.
A JavaScript function is defined with a function keyword, followed by a name for the function and the parentheses ().
Function names follow the same rule as variables. Inside the parentheses, you can include several parameter that
can be accessed in the body of the function inside curly braces. These parameters become the variables inside the
function body. The values provided as argument while invoking the function are assigned to these parameters in the
order.
A JavaScript (JS) function executes the block of code inside it only when it is invoked (or called).
Calling a function involves the function name followed by parentheses and the arguments inside the parentheses.
These arguments are passed to the parameters defined in the function definition.
function add(x, y) {
alert(“Addition”);
var sum = x + y;
return sum;
}
var result = add(2, 4);
In the example given above, a function named sayHi has no arguments, and it simply brings an alert box with the
message “Hello World”. So, when the function is called using the statement sayHi(), it will execute the code, and an
alert box will be shown with the text “Hello World”.
77
JavaScript Functions
Keyword Argument
• The argument keyword is a local variable available for functions (except ES6 functions, which will be covered later).
• You can refer to a function’s arguments using the argument keyword, which is an object type.
• For instance, in the example given below, you will call argument[0] to access the first argument. Similarly, the second
argument will be called using argument[1].
78
JavaScript Functions
Different ways of defining a function
Named function: This is the function declaration and the function invocation (calling) that you witnessed before.
79
JavaScript Functions
Different ways of defining a function
Anonymous function: This process of defining a function involves creating a function without giving it a name. It is
generally used as an argument for other functions. For instance, the JavaScript method of setting a timer setTimeout()
uses anonymous functions.
Recursive function: A recursive function is a function that calls itself until a condition to call itself fails. For instance, a
countdown timer function will call itself until the number becomes 0.
function countdown(num) {
console.log(num);
var nextNum = num - 1;
if(nextNum > 0) { countdown(nextNum); }
}
countdown(5);
81
JavaScript Functions
Method
Have you ever wondered whether or not you can put a function inside an object?
var person = {
firstName: “Prachi”,
lastName: “Agrawal”,
getFullName: function() {
console.log(this.firstName + “ ” + this.lastName);
}
};
person.getFullName();
82
Key Takeaways
• JavaScript (JS) objects are similar to real-life objects (e.g., car) and have properties
(e.g., doors, colours and wheels) and methods (e.g., turn left, turn right and apply
brakes). All the properties of and methods in objects are stored in the “key-value”
format.
• User-defined types (objects and arrays) are passed by reference whereas the primitive
types are passed by value.
• The functions in JS are blocks of code that execute a particular task, such as adding
two numbers. These functions may or may not return a value.
• User-defined types (objects and arrays) are passed by reference whereas the primitive
types are passed by value.
• The functions in JS are blocks of code that execute a particular task, such as adding
two numbers. These functions may or may not return a value.
Thank you!
85