002 web-dev-JS-V2.2-1
002 web-dev-JS-V2.2-1
website: www.inovotekacademy.com
If you're new to programming, javascript is a great language to start with. It's easy to learn and
there are many resources available to help you get started. In section, we'll cover the basics of
javascript, including variables, data types, operators, and functions. By the end of this section,
you'll have a better understanding of how javascript works and be able to write basic programs.
What is Javascript?
Javascript is a programming language that allows you to add dynamic content to your web
pages. That means you can create things like animations, games, and form validation with
javascript. It runs on your web browser and doesn't require a separate download or installation
like some other languages.
Javascript is what's called a "client-side" language. That means the code runs on your computer,
not on the server where the website is hosted. This is in contrast to "server-side" languages like
PHP or ASP, which run on the server before the page is even sent to your browser.
Client-side languages are convenient because they don't require any special setup on the server.
All you need is a text editor and a web browser, and you're ready to start coding!
Javascript is a programming language that is widely used by web developers to create interactive
web applications.
Javascript has a number of benefits that make it a popular choice for web development. It is easy
to learn, versatile, and can be used to create a wide variety of applications. Additionally,
javascript is free to use and is supported by all major web browsers.
If you are considering learning a programming language for web development, javascript is a
great choice. It is a versatile language that can be used to create a wide variety of applications.
With Javascript you can become a frontend, backend and fullstack developer
With Javascript you can create web applications, mobile and desktop apps
JavaScript variables are used to store data values. In JavaScript, data values can be text strings,
numbers, arrays, or objects. Variables can be declared using the var, let, or const keywords.
• var
• let
• const
var keyword
the var keyword is used to create a variable that is globally scoped, meaning it can be accessed
from anywhere in your code.
let keyword
The let keyword is used to create a variable that is locally scoped, meaning it can only be
accessed from within the block of code it was declared in.
const keyword
The const keyword is used to create a variable that cannot be reassigned, making it a constant
value.
Where variableName is the name of your variable and value is the value you are assigning to the
variable. You can also declare
multiple variables on the same line using a comma delimiter like this:
Once a variable is declared, you can assign it a value using the equal sign (=):
myName = "John Smith"; // Assigns the value "John Smith" to the myName variable.
You can also declare multiple variables without assigning values to them by leaving off the value
part of the statement. Variables declared in this way will have a default value of undefined.
var name, age, isMarried; // all variables are assigned the value of undefined by default. /* The
following shows data types */
Here are some of the basic rules that govern JavaScript syntax.
1. JavaScript is case-sensitive. This means that language keywords, variables, function names,
and any other identifiers must always be
typed with a consistent capitalization of letters. The keyword var is not the same as the keyword
var.
2. Statements must end with a semicolon ( ; ). For example, the statement x = 5; is valid, but the
statement x = 5 is not.
3. Whitespace (spaces, newlines, and tabs) is generally ignored, except when it is used to
separate tokens. For example, the statements x=5 and x = 5 are equivalent.
4. Comments can be added to your code to make it more readable. JavaScript supports two types
of comments:
5. Identifiers can be any combination of letters, digits, underscores (_), and dollar signs ($).
However, they cannot start with a digit. In addition, some reserved words cannot be used as
identifiers (e.g., class, return, etc.).
6. Variables must be declared before they are used. This can be done using the keyword var. For
example:
var x; // declares a variable named x var y = 5; // declares a variable named y and assigns it the
value 5
7. Data types in JavaScript include numbers, strings, Booleans (true/false values), and objects.
There are also two special data types: undefined and null.
8. Numbers can be written with or without decimals. For example, 3.14, 42, and -99 are all valid
numbers.
9. Strings must be enclosed in quotes. Single or double quotes can be used, but they must match
(e.g., "hello" and 'goodbye' are both valid, but "hello' is not). Strings can span multiple lines by
using the backslash ( \ ) as an escape character:
"This is the first line.\nAnd this is the second." // produces "This is the first line.<newline>And
this is the second."
11 . Javascript is a text-based language. This means that it is made up of words, numbers, and
punctuation marks that are read by a computer and interpreted into instructions.
• No spacing
Camel case is a naming convention where each word in the name is capitalized, except for the
first word. For example, the variable name “myVariable” would be written in camel case.
When choosing a name for your variable, be sure to avoid using any of the reserved words in
JavaScript. Reserved words are words that have special meaning in the language and cannot be
used as variable names.
Spaces and special characters are not allowed in JavaScript variable names. If you need to use
multiple words to describe your variable, you can use camel case orunderscores to separate the
words (“my_variable”).
• Keep it short:
Long variable names can make your code more difficult to read and understand. When possible,
try to choose a name that is short but still descriptive.
The JavaScript language contains two different types of data: primitive values and objects.
A primitive value is a value that has no properties or methods. A primitive value is immutable,
which means it cannot be changed. The only way to create a new primitive value is to create a
new variable and assign it a new value.
There are the primitive values in JavaScript: undefined, null, Boolean, Number, String, Symbol,
and bigint.
1. undefined
Undefined is a value that represents no value. It is the default value of variables that have not
been assigned a value.
2. null
Null is a value that represents no value. It is used to indicate that a variable does not have a value.
3. Boolean
4. Number
A number is a value that represents a number. All numbers in JavaScript are 64-bit floating-
point numbers.
5. String
String is a value that represents a sequence of characters. Strings are immutable, which means
they cannot be changed. The only way to create a new string is to create a new variable and
assign it a new value.
6. Symbol
Symbol is a unique and immutable value that can be used to identify an object. Symbols are
typically used as keys in objects.
Operators in JavaScript are the symbols that represent certain actions that can be performed on
variables. In JavaScript, there are many different kinds of operators, including arithmetic
operators, assignment operators, comparison operators, logical operators, and Bitwise operators.
Each kind of operator performs a different kind of operation.
Arithmetic operators
Arithmetic operators take two operands (values) and perform an arithmetic operation on them
• Multiplication (*)
• Modulus (%) division with remainder. Example 12%2 would give you 0 as the remainder
while 13%2 would give you 1 as it should be according to division;
Increment (++)
Synthax
• x++ ( postfix) Postfix increment
Postfix increment
If used postfix, the increment operator will first increment the value before returning it.
let x = 3;
y = x++;
// y = 3
// x = 4
Prefix increment
If used as a prefix operator (for example, ++x), the increment operator will increment the
operand and return the new value.
let a = 2;
b = ++a;
// a = 3
// b = 3
Assignment operators
The assignment operator in javascript assigns a value to a variable. The most common
assignment operator is the = operator, which assigns the value to the left of the = to the variable
on the right. For example, if we have a variable called x and we want to give it the value of 5, we
would write x = 5.
Other assignment operators include the += operator, which adds the value to the left of the = to
the variable on the right, and the -= operator, which subtracts the value to the left of the = from
the variable on the right. Example :
You can combine the assignment operator with basic arithmetic operators using the combined
assignment operators ( += , -= , *= , /= , &= , and |= ). This lets you write code like this:
let m=0
m = m + 5 is equivalent to m += 5 .
m = m * 3 is equivalent to m *= 3 .
Example of ==
"" == "0" is true then when comparing string , == will compare only values, not type.
Example of ===
NOTE: These operators evaluate expressions such that they return either true or false :
3 < 5 // evaluates to true 3 > 5 // evaluates to false 3 >= 4 // evaluates to true 2 <= 1 // evaluates
Logical operators
Logical operators allow JavaScript to perform boolean logic on values. These operators are:
• and’‚bb’ : If each of the two operands is true, then the condition becomes true. (a && b)
will be true only if both a and b are true.
• or’‡Ç• : If any of the two operands is true, then the condition becomes true. (a || b) will be
true if either a or b is true.
• not’‚“ Used with boolean values to reverse the value i.e. from false to true, and from true
to false
var x = 2;
// x != 7 is TRUE
Conditional Statements in javascript
What is a conditional statement? A conditional statement is a set of commands that will only be
executed if a specified condition is met.
if (condition) {
} else {
In JavaScript, a truthy value is a value that is considered true when evaluated in a Boolean
context. All values are truthy unless they are defined as falsy. The following values are
considered falsy:
- false
-0
- ""
- null
- undefined
So what does this all mean? Basically, any value that is not one of the falsy values listed above is
considered truthy. This includes values like true, 1, and "foo".
JavaScript Loops
JavaScript loops are a powerful programming tool that allows you to execute a block of code
multiple times. While there are many different types of loops, they all share a common structure:
a condition is checked, and if the condition is true, the code block is executed. This process is
then repeated until the condition is no longer true. In this blog post, we'll take a closer look at
how JavaScript loops work and how you can use them in your own pr
ograms.
The for loop has the following syntax: > The **for** statement creates a loop that consists of
three optional expressions, enclosed in parentheses and separated by semicolons, followed by a
statement or a block of statements.
inal-expression ===incrementer/decrementer
> The **initialization** expression initializes the loop; it's executed once, as the loop begins.
> When the **condition** returns true, the loop executes the statement.
> The **final-expression** is executed every time the statement (s) runs.
Code example :
let i;
The while loop is similar to the for loop, but instead of using an initializer and an incrementer, it
only has a condition. The code block is executed repeatedly until the condition evaluates to false.
while (condition) {
let i = 0;
console.log(i);
i++;
The while loop loops through a block of code as long as a specified condition is true.
while (condition) {
// code to run
i++;
Javascript Functions
What is a function?
In JavaScript, a function is a piece of code that is written to perform a specific task. Functions
are usually self-contained and can be reused across your code. This makes them very important
in JavaScript programming.
Why functions
There are many reasons why you should use functions in JavaScript. Here are 10 of the most
important reasons:
Defining functions
• function declaration or a
• function expression.
function name() {
// code to be executed
// code to be executed
The return keyword is used to exit a function and return a value to the caller.
The return keyword can be used with or without a value. If a value is present, it is returned to the
caller. If no value is present, the function simply exits.
The return keyword is essential for creating functions that return values. Without it, functions
would only be able to perform actions, not return values to the caller.
This would limit the usefulness of functions and make them much less powerful.
So if you're creating a function that needs to return a value, be sure to use the return keyword.
It'll make your function much more useful and powerful.
Function arguments and function parameters are often used interchangeably, but there is actually
a subtle difference between the two. Function arguments are the values that are passed to a
function when it is invoked, while function parameters are the variables that are used to receive
those arguments.
Introduction
Javascript strings are one of the most essential data types in the language. In this guide, we will
explore the various properties and methods associated with strings, as well as how to manipulate
and format string data.
In Javascript, strings are lines of text that are used to store and represent data. Strings can be
anything from a single character to an entire novel—any sequence of characters can be stored as
a string. Strings must always be placed within either single or double quotation marks ( ' ' or " " ).
Strings are commonly used for storing user input, such as when a user enters their name into an
input field on a website.
How to create strings?
Strings can be created in several different ways. The most common way is simply by assigning a
string of characters to a variable:
toLowerCase()
toUpperCase()
String length()
String trim()
The trim() method is useful for removing whitespace from both sides of a string. This can be
helpful for cleaning up user input, or for making sure that two strings are truly equal.
String split()
string reverse()
The reverse() method changes the order of the elements in an array so that the first element
becomes the last, the second element becomes the second to last, and so on.
console.log(text);
String repeat()
The slice() method produces a new string that is a copy of the original string. The original string
is not changed. === making copies of strings
String startsWith()
The startsWith() method is useful for determining whether a string begins with a specified string.
This is important because it can help ensure that a string is the correct format.
For example, if you are expecting a string to be in all caps, you can check to see if the string
starts with a capital letter.
If the string does not start with a capital letter, you know that it is not in the correct format.
str.startsWith("Welcome");
String includes()
concat() Method
slice() Method
The slice() method enables you to select from a given start point up to (but not including) a
given end point. This method does not change the original data.
console.log(ans);
String comparison
In order to compare whether one string is greater than another, JavaScript employs what is
known as "dictionary" or "lexicographical" order.
In other words, strings are compared letter-by-letter.
• First it will check the first letters on both sides if one is greater than the other it will return
true but if they are equal it will move to the next letter until it returns true /false
• Lowercase letters are greater than uppercase letters of the same type Because the
lowercase character has a greater index in the internal encoding table JavaScript uses
(Unicode)
• If both strings end at the same length, then they are equal. Otherwise, the longer string is
greater
• When comparing values of different types, JavaScript converts the values to numbers.
JAVSSCRIPT ARRAYS
arrays are a collection of items in a particular order and can be accessed by index number.
create an array
//or
myArray2[0] = "pizza";
myArray2[1] = "burger";
myArray2[2] = "chicken";
//or
myArray2[1] = "Express";
myArray2[2] = "MongoDB";
console.log(myArray5[0]);
console.log(myArray5[i]);
myArray5.forEach(function (element) {
console.log(element);
});
Array methods
Method 1: push()
myArray6.push("React");
console.log(myArray6);
Method 2: pop()
myArray7.pop();
console.log(myArray7);
Method 3: unshift()
myArray8.unshift("React");
console.log(myArray8);
Method 4: shift()
myArray9.shift();
console.log(myArray9);
Method 5: indexOf()
returns the index of the first element in an array that matches the specified value
console.log(myArray10.indexOf("Express"));
Method 6: lastIndexOf()
returns the index of the last element in an array that matches the specified value
console.log(myArray11.lastIndexOf("Express"));
Method 7: includes()
console.log(myArray12.includes("Express"));
Javascript objects
Objects are variables that hold multiple pieces of information. In JavaScript, objects are created
with curly braces {}.
Creating Objects
person.name = "John";
person.age = 30;
const person2 = {
name: "John",
age: 30,
};
person.name;
person.age;
person.city;
person["name"];
person["age"];
person["city"];
person.name = "Jane";
person.age = 31;
person.city = "Miami";
2. using bracket notation:
person["name"] = "Jane";
person["age"] = 31;
person["city"] = "Miami";
delete person.name;
delete person.age;
delete person.city;
delete person["name"];
delete person["age"];
delete person["city"];
const carObj = {
make: "Ford",
model: "Mustang",
year: 1969,
color: "red",
description: function () {
},
};
What is this?
1. for...in loop:
Syntax:
for (let key in obj) {
//code to run
//Example:
const student = {
name: "John",
age: 30,
};
//-----
console.log(key);
Syntax
Object.keys(obj)
//Example:
const student2 = {
name: "John",
age: 30,
};
//-----
//console.log(keys); //array
Syntax:
//obj.forEach(function(value, key) {
// //code to run
//}
keys.forEach((key) => {
console.log(key);
console.log(`${key}: ${student2[key]}`);
});
Object.values()
/The Object.values() method works opposite to that of Object.key(). It returns the values of all
properties in the object as an array. You can then loop through the values array by using any of
the array looping methods.
//Syntax:
//Object.values(obj)
//-----
Example:
const student3 = {
name: "John",
age: 30,
height: 1.8,
weight: 80,
};
console.log(values);
values.forEach((value) => {
console.log(value);
});
The object.entries() method returns an array of arrays, where each array contains a key and value
pair.
The object.entries() method is useful when you want to iterate over the properties of an object.
Example
const student4 = {
name: "John",
age: 30,
height: 1.8,
weight: 80,
};
console.log(entries);
entries.forEach((entry) => {
console.log(entry);
});
destructuring assignment
console.log(`${key}: ${value}`);
});
Javascript versions
JavaScript was created by Brendan Eich in 1995 and became an ECMA standard in 1997. The
official name of the language is ECMAScript. ECMAScript versions have been abbreviated to
ES1, ES2, ES3, ES5, and ES6. Since 2016, new versions have been named by year
(ECMAScript 2016 / 2017 / 2018).
1. Introduction
7. Conclusion
Numbers can be positive or negative, integers or floats. An integer is a whole number, while a
float is a number with a decimal point.
console.log(num);
const num = 8;
console.log(num);
Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the
largest possible number.
const infinity = 1 / 0;
const infinity3 = -1 / 0;
Numerical operations
const number1 = 10;
const number2 = 2;
const number5 = 2;
Example of NaN
const number11 = 2;
Example2
You can use the global JavaScript function isNaN() to find out if a value is a not a number:
A number in JavaScript is a double-precision 64-bit number that can represent anything from an
integer to a fraction to a very large or very small real number.
Primitive values cannot have properties and methods, but JavaScript treats primitive values as
objects when executing methods and properties. This allows for methods and properties to be
available to primitive values.
toFixed()
The toFixed() method rounds a number to a certain number of decimals and returns a string.
toString()
parseInt()
parseFloat()
• The parseFloat() method parses a string and returns a floating point number.
Number()
6.How would you find the highest or lowest value in an array of numbers?
10.What is the result of calling toPrecision() on a number? 11.What is the result of calling
toLocaleString() on a number?
17.Only valid numeric strings can be converted into numbers, what value is produced when an
invalid string is converted?
18.Is it possible to perform arithmetic operations on non-numeric values? If so, how do they
work?
//
The == operator The === operator The != (= not equal) and !== (not equal value or not equal
type) operators
Math.abs(x)
Returns the absolute value of x. (Thus only positive numbers will be returned,)
Math.round(x)
Math.ceil(x)
Math.floor(x)
Math.sqrt(x)
Math.pow(x, y)
Math.min(x, y)
Math.max(x, y)
Math.random()
Arrow functions
An arrow function expression is a more concise way to write a traditional function expression,
but it cannot be used in all situations.
name: "BMW",
getName: () => {
return this.name;
},
};
// carObj.getName(); //null
2. Arrow functions do not have arguments.
console.log(arguments);
};
this.name = name;
};
function constructor
// function Person(name) {
// this.name = name;
// }
add2(2); //3
2. multiple parameters with expression
3. Multiline statements
let b = 10;
return a + b;
};
let c = 10;
let d = 20;
return a + b + c + d;
};
const user2 = {
name: "John",
age: 30,
};
console.log(name);
console.log(age);
};
displayUser(user2);
console.log(name);
console.log(age);
};
displayData(["John", 30]);
displayData();
Coding challenge 1
};
Spread Operator
The spread operator (...) is a convenient way to copy all or part of an existing array or object into
another array or object.
Spread syntax "expands" an array into its elements, while rest syntax collects multiple elements
and "condenses" them into a single element
console.log(..."hello"); //h e l l o
//console.log(newArr); //[1, 2, 3, 4, 5, 6]
console.log(newArr2); //[1, 2, 3, 4, 5, 6]
Copy an array
arr2.push(4);
The spread operator can be used to spread an object into a list of arguments.
Example 1
const obj = {
name: "John",
age: 30,
};
const obj2 = {
name: "Mary",
age: 25,
};
const obj3 = {
country: "USA",
};
NOTE: if two objects have the same property, the value of the second object will overwrite the
value of the first object. so the last object will be the one that will be used.
CODE EXAMPLE
minimum price
//console.log(max); //30
Function scope in JavaScript refers to the visibility of variables within a function. Variables
declared within a function are only accessible within that function. They are not accessible
outside of the function.
The local scope is created when a function starts executing, and the global scope is created
when your JavaScript code is loaded into the browser. If you create a variable without using the
var keyword, it will be automatically added to the global scope. Like other programming
languages, JavaScript also has something called lexical scoping. This means that nested
functions have access to the outer function’s variables. In other words, functions can access
outer function’s variables but not vice versa
In JavaScript, global scope refers to the root scope of the program. Global scope is the default
scope for variables and functions defined outside of any other scope. This means that variables
and functions defined in the global scope are accessible from anywhere in the program.
There are two ways to create variables and functions in the global scope.
Variables and functions defined in the global scope are accessible from anywhere in the
program. This can be useful for creating utility functions or variables that need to be accessed
from different parts of the program. However, it can also lead to problems if variables or
functions in the global scope are accidentally overwritten or modified.
const user = {
name: "John",
age: 30,
};
return "Hello";
};
Create a function to access the variables and functions in the global scope
function getUserInfo(user) {
`;
console.log(getUserInfo(user));
Create a function to mutate the variables and functions in the global scope
function changeUserInfo(user) {
user.name = "Jane";
user.age = 25;
console.log(getUserInfo(user));
console.log(user);
In JavaScript, block scope refers to the visibility of variables within a code block. A code block
is a set of curly braces {} that encloses one or more statements. Variables declared within a code
block are only visible within that block and are not accessible from outside the block.
One of the most common uses of block scope is with the if statement. The code block associated
with an if statement is only executed if the condition evaluates to true. This means that variables
declared within the code block will only be accessible within the if statement.
Block scope can also be used with functions. Variables declared within a function are only
visible within that function and are not accessible from outside the function.
Overall, block scope is a way of limiting the visibility of variables to only the code block in
which they are declared. This can be helpful in preventing namespace collisions and making
code more readable.
//console.log(i);
Variables that are declared within a function are only accessible within that function. This means
that if you try to access a variable that is declared inside a function from outside the function,
you will get an error.
Function scope is important to understand because it can impact the way your code runs. For
example, if you have a variable that is declared inside a function, you will not be able to access
that variable from outside the function. This can be helpful if you only want a certain piece of
code to run under certain conditions. However, it can also lead to errors if you're not careful.
When you're working with function scope, it's important to keep track of your variables and
where they are declared. This will help you avoid errors and make sure your code
function myFunction() {
console.log(x);
let x = "Hello";
myFunction();
console.log(x);
Lexical scope in javascript
In javascript, lexical scope refers to the visibility of variables and functions in relation to the
lexical structure of the code. That is, the scope of a variable or function is determined by its
position in the code. For example, variables and functions declared inside a function are only
visible inside that function.
Lexical scope is an important concept in javascript because it affects how code is executed and
how variables are accessed. It is also a complex topic, and there are a few different ways to think
about it. In this article, we will explore lexical scope in javascript and how it works.
One way to think about lexical scope is in terms of the nesting of functions. When a function is
declared inside another function, it is said to be lexically nested inside that function. The scope
of the inner function is said to be lexically enclosed by the scope of the outer function. This
means that the inner function has access to the variables and functions declared in the outer
function, but not vice versa.
function myFunction2() {
let x = "Hello";
//console.log(y);
function anotherFunction() {
console.log(x);
// const y = 10;
anotherFunction();
Importance of Scope in js
The main reasons for having different scopes in programming languages are:
- To allow programming in large teams where different people work on different parts of the
code. By hiding some parts of the code (encapsulation), team members working on other parts
of the code are less likely to accidentally break each other's code.
- For performance reasons. It takes time for a computer to look up a variable in an outer scope -
this is called variable lookup overhead. By limiting the amount of code in the same scope, you
can reduce that overhead.
- For security reasons. By making some parts of your code private, you can stop people from
accidentally or maliciously breaking your code
A function is a first-class function if it can be used like any other value in the language. This
means that the function can be:
A function is a higher order function if it takes one or more functions as arguments or returns a
function.
};
console.log(myAnswer(5));
//or
function sayHello() {
console.log("Hello");
console.log("Hello");
};
function sayHello() {
console.log("Hello");
}
const sayHello2 = function () {
console.log("Hello");
};
array[0]();
array[1]();
};
};
return calBillFn;
};
function addTwoNumbers(a) {
return a + b;
};
console.log(myAnswer(5));
//or
const myAnswer2 = addTwoNumbers(2, 5)(2, 5);
Default paramenters
ES5
function addComment(name, comment) {
}
ES6
function addComment(name = "Anonymous", comment = "No comment") {
ES6
function totalBill(base, tax = base * 0.13) {
//es5
function totalBill(base, tax) {
ES6
function makePost(user = "Anonymous", title, body) {
return {
user,
title,
body,
};
History of javascript?
JavaScript was created in 1995 by Brendan Eich while working for Netscape Communications.
It was originally named Mocha, but was later renamed to LiveScript, and then finally to
JavaScript.
LiveScript was renamed JavaScript in the same year, and the language has been known by that
name ever since. In 1996, Microsoft released Internet Explorer 3.0 with support for JavaScript.
In the years that followed, numerous other browsers were released with built-in JavaScript
support, and the language became increasingly popular as a way to add dynamic content to
websites. In 1997, JavaScript was standardized by ECMA International in the ECMAScript
language specification.
In the early 2000s, Ajax and other web technologies were developed that use JavaScript to create
dynamic, responsive web applications. Today, JavaScript is one of the most popular
programming languages on the web and is used for a wide variety of tasks including front-end
web development, server-side scripting, and game development.
Today, JavaScript is one of the most popular programming languages in the world and is used
for a wide variety of tasks including web development, application development, and game
development.
JavaScript's syntax takes after C++ and Java quite a bit. If you have experience with either of
those languages, JavaScript's syntax will look familiar. That being said, JavaScript functions
more like a dynamically-typed, interpreted language like Python or Ruby.
JavaScript is an interpreted language, not a compiled language. A program such as C++ or Java
needs to be compiled before it is run.
The source code is passed through a program called a compiler, which translates it into
bytecode that the machine understands and can execute. In contrast, JavaScript has no
compilation step. Instead, an interpreter in the browser reads over the JavaScript code, interprets
each line, and runs it. More modern browsers use a technology known as Just-In-Time (JIT)
compilation, which compiles JavaScript to executable bytecode just as it is about to run.
JavaScript is named after Java, and many of its concepts are borrowed from the Java language.
However, Java and JavaScript are two entirely distinct languages. The most significant
difference between them is that Java is a compiled language, and JavaScript is an interpreted
language. JavaScript runs on many browsers out-of-the-box, whereas Java applets require an
additional plug-in. Both languages have different runtime environments, different governing
bodies, and different libraries.
While JavaScript has its flaws, it is still a very useful language. It runs in every web browser and
can be used to write cross-platform applications. Additionally, platforms like Node.js allow
developers to run JavaScript on the server side. This means that it is possible to create entire web
applications using JavaScript.
JavaScript can be a complex language, and most teams only use a fraction of JavaScript's
capabilities. If you consult a style guide, it will recommend specific JavaScript techniques,
constructs, and libraries.
javascript Console.log()
JavaScript's console.log() function is used to print text to the console. It can be used to print
simple text, variables, objects, and arrays. The console.log() function is typically used for
debugging purposes.
JavaScript is most frequently executed on webpages inside the browser, but it can also be run
server-side. For now, we will run JavaScript in the console, which will enable us to see the
results of our code more rapidly.
The beauty of interpreted languages is that they are designed to be executed in a single pass
through the source code, running each instruction step-by-step. That means that we can provide
the interpreter with a single step and request that it runs it.
JavaScript consoles were built inside browsers. It is like a command-line interface that runs
JavaScript on your JavaScript engine.
Behind the console is the read-eval-print loop (REPL). This refers to the loop that the console
runs: it first reads your input, then it evaluates it as JavaScript code, then it prints the results. You
will sometimes hear the term REPL being used to refer to any sort of programming shell that
allows you to enter code and see results immediately. For instance, Nodejs, Python and Ruby
also provide similar REPL shells.
Try running some simple math expressions within the console, such as 1 + 2 or 3 * 4. JavaScript
prints the correct answers back at you. Congratulations, you can now use your computer as a
very expensive calculator.
When executing a function in the console ex using the console.log(). It produces two lines of
output. The first line is the results that we expect. The second line reads undefined. This is
because the first line is the output that we instructed JavaScript to print, and the second line is
the result of evaluating our program. Every JavaScript expression has a result, but some
expressions, such as the console.log function, return an empty result called undefined.
Features of javascript?
Example
let myName = "John";
console.log(myName);
};
displayName();
console.log("Hello");
};
sayHello();
This means that the type of a variable can change during the program execution. For example, if
we assign a string to a variable, the type of the variable will be string.
With this, we can use the same variable to store different types of data.
There are no restrictions on the type of data that can be stored in a variable. We can store any
type of data in a variable, unlike in C++.
If you need a strict type checking, you can use typeof operator or you can use typescript.
Example
let a = "string";
let b = 10;
b = true;
It's a programming paradigm that uses objects as the primary way of representing data in a
program which uses Prototypal Inheritance
Prototypes are used to create new objects that inherit properties and methods from another
object.
Array prototype
//----
Array.prototype.push("element");
arr.push(6);
arr.pop();
arr.shift();
Object prototype
1. Object.keys(obj)
2. Object.values(obj)
object hasOwnProperty(property)
Object.prototype.hasOwnProperty("property");
let obj = {
name: "John",
age: 30,
isMarried: false,
};
obj.hasOwnProperty("name");
It's a process that frees up memory by removing objects that are no longer used in the program
and it's called garbage collection.
It's a code that runs concurrently with the code that is running in the background. This means
that the code that is running in the background is not blocked by the code that is running in the
foreground.
But js is a single threaded language. This is possible because of the nature of the event loop.
console.log("Hello");
};
setTimeout(sayHello, 2000);
High-level language
Any applications uses resources like memory, CPU, network, etc. to be run on a computer.
For low level programming languages like C, C++, Java, etc. developers need manage these
resources manually.
For high level programming languages like JavaScript, Python, Ruby, etc. resources
management are done automatically.
//Example
1. Functional programming
2. Object oriented programming
3. Procedural programming
4. Declarative programming
5. Imperative programming
6. Hybrid programming
Javascript Engine
Google Chrome - V8
Code execution in js
source code -> parser -> AST(abstract syntax tree) -> Compilation(convert AST code) ->
machine code -> interpreter -> browser
parser: It's a program that converts the source code to an abstract syntax tree.
AST: It's a tree that represents the code.
Compilation: It's a program that converts the AST code to machine code.
interpreter: It's a program that executes the machine code by reading it line by line.
browser: It's a program that executes the interpreter(display the result to user).
//Since js is not a compiled language, it doesn't have a compiler but instead modern browsers
uses what is called Just-In-Time (JIT) compilation, which compiles JavaScript to executable
bytecode just as it is about to run.
Your script doesn't transform to machine code directly. JavaScript runs on virtual machine V8
(it's true for chrome and classic nodejs) and you can get VM byte code using:
ANSWER
Your script doesn't convert to machine code directly. JavaScript operates on virtual machine V8
(this is true for chrome and nodejs) and you can obtain VM byte code by using: node --print-
bytecode script.js
JS Runtime (Browser)
JS runtime, in a laymans point of view, it's a box that contains all the things we need to run our
code.
EXAMPLE
1. The browser
2. The console
5 Callback Queue(contains all the callbacks that are waiting to be executed eg: setTimeout,
setInterval, button click, when the button is clicked, the callback is added to the callback queue,
when the stack is empty, the callback is executed and this uses a technique called the event loop.
The event loop takes callbacks from the callback queue and puts them in the stack.)
6. Event Loop: This helps us to implement non-blocking code and concurrent code.
7 . WEB APIs are the APIs that are provided by the browser, it's not part of the JavaScript
language but it adds more functionality to the JavaScript engine.
Call Stack in js
A call stack is a data structure that is used to track the execution of function calls. It is used to
keep track of the order in which function calls are made.
When a function is called, it is added to the top of the call stack. The function then gets executed
and, when it is finished, it is removed from the top of the stack. This process continues until the
call stack is empty and all of the functions have been executed.
There are two types of code - synchronous and asynchronous. Synchronous code is executed in a
linear fashion, one line at a time. Asynchronous code, on the other hand, can be executed out of
order or in parallel.
Both synchronous and asynchronous code have their benefits and drawbacks. Synchronous code
is typically simpler to write and understand, but it can be slower to execute. Asynchronous code
can be more complex, but it can also be faster and more scalable.
The key distinctions between asynchronous and synchronous processes are as follows:
Asynchronous processes are multi-threaded, meaning that multiple operations or programs can
execute concurrently. Conversely, synchronous processes are single-threaded, so only one
operation or program can run at a time. Additionally, asynchronous processes are non-blocking,
meaning that they can send multiple requests to a server without waiting for a response.
The setTimeout() function is used to set a delay for a certain action. It can be used to delay an
action by a set amount of time or to delay an action until a certain point in time. The
setTimeout() function is part of the window object and can be used with any other object.
The setTimeout() function takes two arguments. The first argument is the code to be executed.
The second argument is the delay in milliseconds. The code to be executed can be a function or
a string. If the code is a function, it will be executed with the same this object as the
setTimeout() function. If the code is a string, it will be executed as if it were a part of the
setTimeout() function.
The setTimeout() function will return a numeric id that can be used to cancel the delay.