JavaScript
Home
Footer
Operators- arithenatic, logical comparison
Logical Operators and or not
False if -
- undefined
- null
- 0
- "
- false
All other are true
FUNCTIONS - declare and invoke(call)
way of creating a function 1 - function Declaration
- funcion keyword
- fun name
- parameter
- body
- EXAMPLE - function fnName(parameter){body}
way of creating a function 2 - function EXpression
- keyword - let/var
- variable name
- function keyword- function
- parameter
- body
- EXAMPLE - let fnName = function(parameter){body}
Function - Parameters and Arguments
Return Keyword
Let's say that I want to display the result of my function into the main webpage!
We haven't talked about Dom manipulation, so spare me with that.
I'm going to give you some some scenarios why this function is not performing the way we want it.
That's the scenario, number one.
And also, what about say that?
Oh, no, I don't want this play my result into the page, but instead I want to display it inside an
elect.
How can we do that?
In that way, we need what is called the return keyword, because a function with no return and only consol.log is
not giving out anything.
Its just printing the thing in console tab.
So the return keyword is used to exit a function and return a
value to the caller.
Here comes.
So one point of return is it is used to exit a function.
And then if a value is present in the return, it is going to give out to the variable we assign a function to
The return keyword is essential for creating functions that return value.
So without return keyword, function will only be able to perform actions but not return values to the caller.
This would limit the usefulness of a functions and make them much less powerful.
so when you return sommething from teh function, now you can use the returned value anywhere in the javascript
to display on screen,lets say alert(fnName(argument)) and you can displlay the returned value in alert section
of website. Thsts amazing
STRINGS
Ways of creating a string
- using string literal "" or ''
- using the constructor function i.e.
const name = new String("something");
this will return a way
different form of string proved in the javascript code snippet below:
const myName = "John";
const firstName = new String("John");
const result = myName === firstName;
console.log(result);
This code will give false!!!Yeass, though John and John are similar, due to they are
different forms of string literals! . but if you did
const result = myName == firstName;
instead the
answer will be TRUE! because now the datatypes of "John" will not be matched instead just the string.
String Concatenation
- using + operator : str1+str2
- using concat method : const result = str1.concat(str2);
JS Template Literals
- String literals ""
- back tick literals- this is multiline string that is all the enters will be considered ``
- template string
- INTERPOLATION - to use a variable inside the string
- Using ${} between strings
const welcome = "Good Morning ${name}";
- Using + Operator
const welcome = "Good morning" + name ;
String length - it takes white spaces into consideration!
const str = "Hell ";
str.length;
this will give 12
Some String functions
- trim - to remove white spacings
- toUpperCase
- toLowerCase
- indexOf
- split(ch,3) - to split every charachter in the string w a specific characther ch example:
str =
"hobnbkbsf"; str.split("b");
this will give ['ho', 'n', 'k', 'sf'] i.e. all b are splitted
- str.join("b");
- str.reverse(); - to reverse an array.
if you want ot reverse a string, 1) split it into array 2)
reverse it 3) join it into a string!
- str.repeat(n); to repeat a str n number of times
- str.startsWith(ch); - to check if str starts with ch
- str.endsWith();
- str.includes(ch); - to check if str contains ch
- str.slice(n,m); takes n to m charachetes from str
String Comparison
Arrays
Methods of cerating Array
- Using new keyword:
const arr_name = new Array();
- Using Array literal
const arr_name = [];
Array can take any type of data type value
Array Methods
- arr.push(); - add to the end
- arr.pop(); - remove from the end
- arr.unshift(); - add to the beginning
- arr.shift(); remove from the beginning
- arr.indexOf();
- arr.lastindexOf();
- arr.include()
- arr.reverse()
- Reduce Method -
- A function that accepts upto 4 arguments, the reduce method calls the callbackfn function one time
for each element in the array
- Calls the specified callback function for all the elements in the array
- The return value of the callback function is the accumulated result, and is provided as an argument
in the next call to the callback function
- Return a single value
- Doesn't mutates the original array
- Syntax-
arr.reduce(function(acc,currVal,currIdx,arr){},initialVal);
- const callback = (accumulator, currentValue, index) => {
// return something here
}
const result = array.reduce(callback, initialValue)
- The previous return value is used as the next accumulator
- initialValue is the value you want to start with.
accumulator is the value returned from the previous iteration.
It will be initialValue for
the first iteration.
currentValue is array item in the current iteration.
- Find Method
- (method) Array(number).find(predicate: (value: number, index: number, obj: number[]) => unknown,
thisArg?: any): number | undefined (+1 overload)
- Returns the value of the first element in the array where predicate is true, and undefined
otherwise.
- @param predicate
find calls predicate once for each element of the array, in ascending order, until it finds one
where
predicate returns true. If such an element is found, find immediately returns that element value.
Otherwise, find returns undefined.
- @param thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not
provided,
undefined is used instead.
- array.find(function(currentValue, index, arr),thisValue)
- currentValue Required.
The value of the current element.
- thisValue Optional. Default undefined.
A value passed to the function as its this valu
Filter Method
same as find, but this returns an array of answers not just first outcome
Example
const arri = [2, 4, 5, 2, 4];
const reduce = arri.reduce(function (acc, currVal) {
return acc + currVal + currVal;
}, 0);
const find = arri.find(function(elements){
return elements>4;
})
const filter = arri.filter(function(element){
return element> 2;
})
Answers
reduce = 34, find = 5, filter = [4,5,4]
Objects
Accessing Object Properties
const person = { name: 'johny', salary: 45452, hobby: ['dance','cooking']};
- Using dot notation i.e. person.name
- Using Bracket notation i.e. person["name"]
Updating Object property
person.name = "whateve"
person['name'] = 'wahhah' -> used widely since it is more dynamic
for example
let printObj = function(obj){
for(let key in obj){
console.log(`${key}: ${obj[key]}`);
}
}
is better than
let printObj = function(obj){
for(let key in obj){
console.log(`${key}: ${obj.name}`);
console.log(`${key}: ${obj.age}`);
}
}
Deleting Object property
use
delete person.name
that is it, done!
this keyword
in javasctipt 'this' keyword refers to immediate or parent object
if you do console.log(this); randomly it will show global object that is Window
Iterating Over Objects
- for in loop - for(let key in objectName){}
for(let key in person){
console.log(key);
}
- object.keys let ans = Object.keys(objectName);
let keys_array = Object.keys(person);
console.log(keys_array);
- forEach -
keys_array.forEach(function(element){
console.log(element)
})
- object.values - Object.values(person)
- object.entries - Object.entries(person)
Example
let objentries = Object.entries(person);
objentries.forEach(function([key,value]){
console.log(`${key}: ${value}`);
})
Math Objects
- abs
- round
- ceil - upper val
- floor - removes decimal no.s
- sqrt
- pow
- min
- max
- random
- Formula for Random Number between two values:
Math.random() * (max-min + 1) + min
Data Mutation
Array Methods
- arr.forEach(function(item,index,array){})
Array of Objects
An array made up of objects, hence the methods of this are different
functions:
- forEach
- push(object)
- map()
- filter()
- reduce()
Javascript Versions
- ECMAScript 1 2 3 4 5 6
- Array Destructuring
- Object Destructuring
- Destructuring with default values
- Destructuring Parameters
- Rest Parameters - way to pass an arbitrary number of arguments to a function - one function can take only
one rest parameter
- Spread Operator
Array Function
()=>{}
more concise way of writing a traditional function expression, but it cannot be used in all situations.
Limitations
- Do not have this keyword
- Do not have Arguments
- Cannot use as a constructor
Spread Operators
The spread operator (...) is a convenient way to copy all or part of an existing array or object into another
array or object
Spread suntac expands an array into its elements, while rest syntac collects multiple elements and condenses them
into a single element
Javascript History
- JavaScript was created in 1995 by Brendan Eich
- In 1997, JavaScript was standardized by ECMA International in the ECMAScript
language specification.
- It was originally named Mocha -> LiveScript ---> JavaScript.
- In 1997, JavaScript was standardised by in the ECMAScript language specification.
- In the early 2000s, Ajax were developed that use JavaScript to create dynamic applications
- JavaScripts syntax is heavily inspired by C++ and Java.
- JavaScript is an interpreted language, not a compiled language(like Java, which is executed by a compiler,
whereas javascript is interpreted line by line and then run)
- JavaScript is named after Java, and many of its concepts are borrowed from the Java language
console
It is a command line interface that runs js on your js engine
REPL - READ EVALUATE PRINT LOOP is the loop that console runs
if you do console.log('helo') on console, you'll get helo undefined
the helo is result of evaluating our program, the undefined is returned function of the funcction, and the
console log is returning undefined unless specified
Characteristics of Javascript
- Its is interpreted language not compiled
- It is a single threaded language - executes code line by line (this doesnt decrease performance, will prove
ahead how)
-
It is dynamically typed language - i.e. type of a variable can change during the program execution (if you
dont want this you can use a language called Typescript)
- Object Oriented Language - it is a programming paradigm which uses objects as the primary way of
representing data which uses Prototypal inheritance (like push pop methods etc)
- It is called a garbage collector - process that frees up memory by removing objects that are no longer used
in the program and it is called garbage collection
- It is a client side language - using js in browser i.e chrome edge mozilla safari
- It is a server side language - using js on server ie. nodejs
- It is a non blocking - it is a code that runs concurrently in the background with the help of event
loop for example - setTimeout(()=>{}, );
console.log("before");
setTimeout(function (){
console.log(500);
}, 2000);
console.log("after");
This wont print before 500 after, instead this will print before after 500 . so this way we can run
concurrent codes using event loop.
- It is a high level language - resource management are done automatically
- Multi Paradigm Language - i.e. we have difference style of approach how we can structure our code
This
is a coding approach to structure code-
- Functional Programming
- Object Oriented Prog
- Procedural Programming
Javascript Engine
is a computer program that runs js code, since computer understands only machine language i.e. 0 and 1 . All
browsers have a built in javascript engine
- Chrome - V8
- Firefox Mozilla - Spider Monkey
- Internet Explorer - Chikara opera or Presto
code execution process/p>
- source code - jo we wrote
- through parser -> AST (abstract syntax tree)
- through compilation -> machine code
- through interpreter -> browser
Javascript Runtime (Browser)
in a laymans language means a box containing all the things we need to run our code.
The components-
-
Javascript Engine -
- Call Stack
- Heap
- WEB APIs
- DOM
- Timers - setTimeout/setInterval
- Callback Que - contains all the callbacks that are waiting to be executed
- Event Loop - Event Loop helps us to implement non-blocking code and concurrent code.
Javascript Callstack - 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.
Advanced Functions
Types of Scope
Global scope
Block Scope
Function Scope
Lexical Scope
First Class citizens -
-
function returning function
function fcc()
{
return function (a,b)
{ return a+b;
};
}
To call - fcc()(3,4);
- assigning function to a variable -
function smt(){
console.log("helo");
}
const jk = smt;
jk();
smt()
- store function inside an array
High order functions HOF - functions accepting functions as arguments also called as callback functions
- most common -
- reduce
- find
- filter
- map
Function returning a function
immediately Invoked Function Expression IIFE - - A FUNCTION that is gona be executed as soon as your page loads