Javascript Basics: How To Run Javascript Code?
Javascript Basics: How To Run Javascript Code?
Just like any other language, source code needs to be converted into machine language. There are 2 methods to do that:
i. Classic way (in the browser)
index.html with a <script> tag which includes a src attribute which contains the path to the script.js file
script.js which contains the code
In this method we run a html file in the browser, and the browser's js engine runs the js file
ii. Js Engine
This method allows us to run javascript code outside of the browser
E.g.: V8 (by google), Spider Monkey (by mozilla), node
History of javascript
Variables
const is used to make a variable constant, we can not change the value of a constant variable
let is used to constrain the scope of a variable to the scope in which it is declared, it is frequently used for counter
variables in loops
{
var birthYear = 2001;
var currYear = 2021;
let age = currYear - birthYear;
console.log(age); // 20
}
console.log(birthYear, currYear); // 2001 2021
console.log(age); // ReferenceError: age is not defined
Single-line comment
// This is a comment
Multi-line comment
/* This is a
Multi-line comment */
Datatypes
1. Strings
2. Boolean
3. Number
4. undefined
var marks;
console.log(marks); // undefined
Printing to Console
Operators
Arithmetic operators
1. Addition ( + )
2. Subtraction ( - )
3. Division ( / )
4. Multiplication ( * )
5. Modulus ( % )
6. Exponential ( ** )
Relational operators
1. Equality ( == )
2. Inequality ( != )
3. Strict equality/Identity ( === )
4. Strict inequality/Non-identity ( !== )
5. Greater than ( > )
6. Less than ( < )
7. Greater than or equal to ( >= )
8. Less than or equal to ( <= )
Logical operators
1. AND ( && )
2. OR ( || )
3. NOT ( ! )
typeof operator
NOTE: typeof null returns object as all objects are derived from null
Read this
if (condition) {
// true statements
} else {
// false statements
}
switch case
switch (expression) {
case expression:
// true statements1
break;
case expression:
// true statement2
break;
default:
// default statement
}
Looping Statements
for loop
while loop
var myObject = {
myMember1 = 1,
myMember2 = 2,
myMember3 = 3,
}
for (var member in myObject) {
// looping statements
}
Type Coercion
While using conditional expressions it should be kept in mind that non-boolean values are coerced to boolean values in a
boolean context
falsy values are values that get coerced to false . A few examples of falsy values are 0 , -0 , empty string value ( "" ,
'' , or `` ), null , undefined , NaN
truthy values are values which are not falsy
NOTE: when the 1st operand in a Logical AND ( && ) operation is falsy, the result is the falsy value
Coercion to String
When a string and a non-string value are concatenated/added the non-string value is coerced into a string, and then both
values are concatenated
console.log("go"+2); // go2
console.log(6 + '8'); // 68
console.log(true + "fru"); // truefru
console.log("something" + null); // somethingnull
console.log(undefinedVariable + ":("); // undefined:(
console.log(NaN + `MaN`); // NaNMaN
NOTE: true , false , null , undefined , NaN coerced into strings are just strings containing the name of the value
Coercion to Number
When a subtraction ( - ), multiplication ( * ), division ( / ) or modulus ( % ) operation is performed, all non-number operands
are coerced into numbers; as these operations can only be performed on numbers
console.log("100"-31); // 69
console.log(' 8.99' - `0.00000001 `); //8.98999999
console.log('2' * "abc"); // NaN
console.log("10" / "5"); // 2
console.log("10" % "5"); // 0
console.log(99 * null); // 0
console.log(100 - true); // 99
console.log(false * 8); // 0
NOTE: null coerced into a number is 0, undefined coerced into a number is NaN
NOTE: true and false coerced into numbers are 1 and 0 respectively
NOTE: boolean and falsy values can also be added with numbers. But strings can not implicitly be added with numbers
because when performing addition the number is coerced into a string.
Equality operator
When datatypes of the operands are not the same, the non-number operands are coerced into numbers and then compared
Functions
function functionName() {
// statements
}
functionName();
We can reference a function by name without parenthesis
functionName;
The return keyword can be used to return a value from the function
function functionName() {
// statements
return value;
}
console.log(functionName()); // value
Functions are available globally, but when a function is stored in a variable it is not available globally
Context
Types of contexts
1. Global context
It is responsible for collecting information
2. Execution context
It is responsible for executing code
For single-line of code like console.log() , an execution context is created and then destroyed once the code has
completed execution
For a function, a larger execution context is created, all the code within the function is executed inside the functions
execution context, the execution context is destroyed once the function completes its execution
Scope chaining
Technically a scope is defined by curly braces ( {} ) but only functions behave as scopes in scope chaining
Scope chaining is a feature of execution contexts which enables inner/smaller scopes to access information that exists in
outer/larger scopes when the information is not present in the smaller scope
The scope of a function is based on where the function is defined, and the information that a function can access is also
based on where it is defined.
Arrays
console.log(arrayName1[0]); // 'value1'
arrayName1[0] = 1;
console.log(arrayName1); // [1, 'value2', 'value3']
1. length
Stores the number of elements present in the array
js var myArr = [1, 2, 3, 4, 5]; console.log(myArr.length); // 5
2. pop()
Returns and removes the last element from the array
js console.log(myArr); // [1, 2, 3, 4, 5] console.log(myArr.pop()); // 5 console.log(myArr); // [1, 2,
3, 4]
3. push()
Adds an element to the end of the array, and returns the updated length of the array
js console.log(myArr); // [1, 2, 3, 4] console.log(myArr.push(5)); // 5 console.log(myArr); // [1, 2,
3, 4, 5]
4. unshift()
Shifts all elements to the right and adds the element passed to it as an argument as a new element at the 0th index, and
returns the length of the array
js console.log(myArr); // [1, 2, 3, 4, 5] myArr.unshift(0); console.log(myArr); // [0, 1, 2, 3, 4, 5]
5. shift()
Shifts all elements to the left, and removes and returns the element at the 0th index
js console.log(myArr); // [0, 1, 2, 3, 4, 5] console.log(myArr.shift()); // 0 console.log(myArr); //
[1, 2, 3, 4, 5]
6. indexOf()
Takes a value as an argument, searches for it in the array and returns the index of the element if it matches the given
value, if the value does not exist in the array it returns -1
js console.log(myArr); // [1, 2, 3, 4, 5] console.log(myArr.indexOf(1)); // 0
console.log(myArr.indexOf(9)); // -1
7. slice()
Returns a slice of the array, starting from the given beginning index (include) and ending before the ending index
(excluded)
default value of the ending index is the length of the array
js console.log(myArr); // [1, 2, 3, 4, 5] console.log(myArr.slice(1,4)); // [2, 3, 4]
console.log(myArr.slice(2)); // [3, 4, 5]
8. splice()
Returns and removes a part of the array, and replaces it with the provided values
The part to remove is specified by a starting index, and the count which denotes the number of elements to remove
js console.log(myArr); // [1, 2, 3, 4, 5] console.log(myArr.splice(1, 2, "2", "3")); // [2, 3]
console.log(myArr); // [1, '2', '3', 4, 5]
9. fill()
Replaces a slice of the array with a value, and returns the result, if the ending index is not provided the length of the
array is taken
js console.log(myArr); // [1, '2', '3', 4, 5] console.log(myArr.fill(null,1,3)); // [1, null, null, 4,
5]
10. filter()
Takes a call back function as an argument and returns an array of elements for which the function returns truthy
js console.log(myArr); // [1, null, null, 4, 5] console.log(myArr.filter((e) => typeof e == 'number'));
// [1, 8, 8, 8]
11. every()
Takes a call back function as an argument and returns true if the function returns true for every value of the array else it
returns false
js console.log(myArr); // [1, null, null, 4, 5] console.log(myArr.every((e) => e >= 0)); // true
12. forEach()
Takes a call back function as an argument to which we can pass elements of the array, the call back function will be run
for all elements of the array
js console.log(myArr); // [1, null, null, 4, 5] myArr.forEach((element) => console.log(typeof element))
// number // object // object // number // number
1. Array.from()
Creates an array from any iterable (like a string)
js console.log(Array.from('hello')); // [ 'h', 'e', 'l', 'l', 'o' ]
Objects
// normal syntax
var objectName1 = {member1: "value1", member2: "value2"};
// commonly used syntax for increased readability
var objectName2 = {
member1: "value1",
member2: "value2",
}
var myObj1 = {
'member1': 1,
"member2": true,
}
Member functions/methods can be defined by writing the name as a key and an anonymous function as the value
The this keyword can be used to refer to the object from inside a member function
var myObj2 = {
sum: 0,
add: function (num1, num2) {
this.sum = num1 + num2;
},
}
Members of an object can be accessed either by using the dot operator ( . ) or by writing the member name in a string
inside square brackets ( [] )
this keyword
What is DOM?
1. getElementById()
The getElementById() method of the document object returns an object of the element that matches the id
It takes a string containing the id as an argument
js document.getElementById("id_to_search");
2. getElementsByXXX()
The getElementsByXXX methods of the document object returns an array of objects which match the given condition
Elements can be filtered on the basis of ClassName , Name , TagName and TagNameNS
It takes a string containing the value to filter on as an argument
js document.getElementsByClassName("className_to_search");
document.getElementsByName("element_to_search"); document.getElementsByTagName("tagName_to_search");
document.getElementsByTagNameNS("tagName_to_search");
3. querySelector()
The querySelector() method of the document object returns the first occurrence of an element which matches the
given conditions
Conditions to filter elements are written in a string and passed to the method
to select a particular html tag the tags name can be written
to select an element of a particular class the class name can be written preceded by a dot ( . )
to select an element with a particular id the element's id can be written preceded by a hash ( # )
When multiple values are passed for finding, it finds the element which satisfy all conditions
js document.querySelector("h1"); // returns an object of a h1 tag document.querySelector(".title"); //
returns an object of an element of the title class document.querySelector("#submit-button"); // returns
an object of an element with the submit-button id
4. querySelectorAll()
It is the same as querySelector() but returns an array of objects of all elements which matched the conditions