Download as pdf or txt
Download as pdf or txt
You are on page 1of 61

Javascript

fundamental
Course Target
1. Understanding Javascript Concept
2. Understanding Variable
3. Understanding Data Type
4. Understanding Array
5. Understanding Conditional
6. Understanding Looping
7. Understanding Type Conversion
8. Understanding Function
9. Understanding Object
10. Understanding Class
Javascript introduction
JavaScript is a programming language used in website
development to be more dynamic and interactive. if
previously you only know HTML and CSS, with JavaScript
can increase functionality on web pages.

With JavaScript you can create applications, tools, or


even games on web.
Running javascript on browser
Right click on the browser select inspect ( Ctrl + Shift + i )

Open the console tab menu


How can we run our JavaScript code?
what is javascript used?

or

compiler intepreter
what is javascript used?

intepreter
let's start use Javascript
Download and Install NodeJS
Node.js is Ryan Dahl's platform for running applications
JavaScript-based web which was introduced in 2009. With
this platform, you can run JavaScript from the server side.

Test your node successfully installed with this command:


Node JS vs Javascript
Node.js and JavaScript are two things different.
Node JS vs Javascript
JavaScript is used together with HTML and CSS to create web pages that
are interactive.

Node.js, on the other hand, is a platform for running code JavaScript on


the server side. It is responsible for executing code JavaScript before the
website page is displayed in the browser.

Node.js can run websites, web applications, and games browser-based


with high performance.
Tried using node

open terminal/ command prompt


Variable
Variable
A variable is a name that represents a value. Naming
variables in javascript usually have 3 types viz
const
the value of the variable
can’t be changed.

var
Block Scope
const name
is an old-school variable declaration
function Scope
can Redeclared
let
is a modern variable declaration.
can Reassign
can Reassign
can Hoisting Block Scope
var name
let name
Introduction Hoisting
hoisting is appointment a variable before called
Block Scope vs Function scope
Block scope is an activity limit that is delimited by brackets
curly braces in a for loop or if condition or a variable.
Block scope = let, const

Function scope is a limitation of activities within a


function delimited by curly braces.
Function scope = var
Local variabel vs Global variabel
A variable declared inside a function is only visible inside that function

Global variables are visible from any function (unless shadowed by locals).
Data Type
Data Type
Data types are the types of data that we can store in variables
Primitive data types can store only one value at a time.

String Number Boolean

Undefined Big Integer

Non-primitive data types can store more than one value at a time

Object
Operator
Operators are symbols that are used to perform operations
on values ​and variables.

Arithmetic operators Comparison operators


+ - * ** / == != > < ====

Assignment operators Logical operators


|| && !
=
String operators
+
example
Comparison operators
example
Logical operators
OR operators
AND operators

NOT operators
Array
Array
Array is a structured data type that functions to store
a number of data or elements where each element has an index

Elements in an array in javascript can have different data types

declaration :
let students = new Array()
let students = []
Array Method
push add array elements at the following index

pop remove last element

shift delete the first element

unshift adds items to the beginning

splice add new elements according to index.

slice remove elements according to index


Displays the entire contents of the array

Let arr = [‘sony’, ‘nikon’, ‘Fujifilm’]

for(let i = 0; i < arr.length ; i++){


console.log(“Mahasiswa ke-” + (i+1) + “ : “ + arr[i])
}
String Manipulation

extracts a part of a string and returns the extracted part in a new string

Slice Substring Substr


String.slice(start,end) String.substring(start,end) String.substring(start, length)

CharAt BackTik
array.CharAt(index) ` this code ${expression} `
Conditional
If Else Statement
If is a key for branching, which means we can execute certain
program code when a certain condition is met.

let nilai = 90;


if (nilai > 80) { console.log('nice'); }

if we want to execute a certain program if the condition evaluates to


false, this can be done with an else expression

if (nilai > 80) { console.log('nice'); }


else if (nilai > 60 ) { console.log('standard'); }
else { console.log('Try again'); }
Switch Case Statement
A switch statement can replace multiple if checks.
It gives a more descriptive way to compare a value with multiple variants

if (condition1) { switch (ecpression) {


action case value1 :
} action
else if (condition2 ) { break;
action case value2 :
} action
else if (condition3) { break;
action default :
} action
else { } break;
}
Ternary Operator
shorthand for the if branch, but shorter and to the point

if condition ? " true " : "false"


Looping
Looping
is the process of repeating the execution of one statement or more blocks of statements
without stopping, as long as the conditions referred to are met

In general, this loop is divided into two. Namely, calculated loops and
uncountable loops.

calculated loops uncountable loops.


For while
Foreach do while
Repeat
For
for(init statement; condition; post statement){
// block looping
}

Init statement
will be executed only once at the start before the loop
Post statement
will be executed after each loop
While Do While

while (condition) { do {
// block looping // block looping
} }
while(condition)
Arrays Loop
Let arr = [‘sony’, ‘nikon’, ‘Fujifilm’]

for(let i = 0; i < arr.length ; i++){


console.log(“Mahasiswa ke-” + (i+1) + “ : “ + arr[i])
}

But for arrays there is another form of loop, for..of:


Let arr = [‘sony’, ‘nikon’, ‘Fujifilm’]

for(let camera of arr){


console.log(camera);
}
Type Conversion
Type Conversion
is a method to convert data type

String Conversion Boolean Conversion


Numeric Conversion

let variabel_name = New_Data_Type(value)


Function
Functions
is a set of code blocks wrapped under a specific name for a
specific purpose to make the code more modular and reusable

Function Creation Rules

Functions are created using the camelCase writing format

function name must contain a verb or verb.


Functions Category

Built-in function User-Defined func

This is a custom function that is not


Is a function that has
built in to javascript. created Using
been provided by
the function keyword, Parameters /
javascript
arguments, Function body wrapped
by {} and Can return value (return
slice(), splice(), substring() value) or not

Function declaration
Function expression
Functions Declarations
The function keyword goes first, then goes the name of the
function, then a list of parameters between the parentheses
(comma-separated, empty in the example above) and finally the
code of the function, also named “the function body”, between
curly braces

function sayHello() {
console.log("Hello Enigmanians ! ");
}
Functions Expression
is a function stored in a variable.

const sayHello = function (name) {


Console.log("hello " + name);
}
Parameter & Argument

Parameters
Variables that are written in brackets when the function is
created, used to hold the value passed during the function sent
function sayHello(name) {
console.log("Hello " + name);
}

Argument
The value passed to the parameter when the function is called
sayHello('Enigma') ;
Lexical scope
The lexical scope is the scope that is read when the JavaScript code is
going through the compile process, or often called compile-time. This
lexical scope regulates in which scope we have to look for a variable.

example
var x = 2;
var add = function() {
var y = 1; return x + y;
};
Arrow Function
ES6 introduced a new function called arrow function. Arrow
functions are similar to normal functions in behavior, but
differ in the way they are written. As the name implies,
functions are defined using arrows or fat arrow =>

before using arrow function


const hello = function() { const hello =() => {
return 'hello enigma' return 'hello enigma'
} }

arrow function with parameter


const hello =(name) => "hello "+name
IIFE (Immediately Invoked Function
Expression) is a function an
expression that is immediately
called upon creation

IIFE vs SIAF
SIAF (Self Invoking Anonymus Function) is
when there is a the variable insidethe
function is not named then the variable is
not accessible outside
Object
Object
An object can be created with figure brackets {…} with an optional list of
properties. A property is a “key: value” pair, where key is a string (also called a
“property name”), and value can be anything.

We can imagine an object as a cabinet with signed files. Every piece of data is
stored in its file by the key. It’s easy to find a file by its name or add/remove a file.

// bad
const user = new Object(); // object structural syntax

// good
const user = {}; // object literal syntax
Accessing Object
const user = {
fullName: 'Ramadhan',
age: 22,
isActive: true
startRun: function(){
console.log(“1 2 3 go!”)
}
}

To access the value of an object property, we can call the object


name and then a period or use square brackets
Console.log(user.fullName);
Console.log(user['fullName']);

to access object method using the ()


Console.log(user.startRun());
Modify an object.
When we change an object using the assignment operator and its property/key already
exists, the value in it will be replaced with the new value.

user.fullName = 'Rohkmah'
Meanwhile, if the property with the specified key name is not found, then a
new property will be added to the object.

user.email = 'user@gmail.com'
We can also delete properties on objects by using the delete keyword

delete user.email;
Keyword this
The this keyword here refers to the owner of the function itself.
const student = {
name : 'Anis' ,
address: { city: 'Dewata' }
console.log(`${this.name}`)
}
The call, apply, and bind methods are used to access data from other objects that differ in context (this)
function getInfo(address) {
console.log(this.address.city);
console.log(`My address is ${address.city}, ${address.province}`); // error
}

getInfo.call(student, student.address);
getInfo.apply(student, [student.address]); ]
Immutable Object
By default objects in JavaScript are mutable
If we create a new variable and we immediately assign an object, the new
variable only copies that object by reference, does not copy its value

There are 2 ways we can copy object references and their values:

use the keyword Object.assign()


const car = {
name: 'terrios'
}
const newCar = Object.assign({}, car);
newCar.name = 'BMW';

using the latest feature from ES6 namely Spread Operator


const newCar = { ...car };
Class
Class
Is a framework or blueprint for creating an object
CREATE CLASS
Before ECMAScript 6, JavaScript was procedural, where we could print an
object using a function, in ES6 we could print the object using a class.

before ES6 - Constructor Function with keyword class

function Car() { class Car {


this.name = '' }
this.run = function () {
console.log('Car is running');
const corolla = new Car();
}
}
const terios = new Car();
Constructor Class
Each class always adds a constructor to create a objects from classes.
When the new keyword is called, the constructor will be executed.
1 class can only have 1 constructor

class Car {
constructor(brand) {
this.brand = brand;
}
engineStart() {
console.log(`${this.brand} ${this.name} engine started`);
}
}
const corolla = new Car('Toyota');
corolla.engineStart() // Toyota Corolla engine started
Class static method
A method that can be used without having to initialize the object first

class Model extends Mobil {


constructor(brand, mod) {
super(brand);
this.model = mod;
}
static hello(){
return “hello”
}
}

Model.hello()
Inheritance (derivative)
Using the extend keyword
class model is the lower class or child of the car
The model class accesses whatever is in the parent

class Hewan {
berjalan(name) {
console.log(`${name} berjalan`);
}
}

class Kucing extends Hewan {


}

const kucing = new Kucing()


kucing.berjalan('kucing');
Super Keyword
The super keyword is used to call the constructor of the super class or
parent class. If in the child class we create a constructor, it is mandatory
to call the parent constructor, even though there is no constructor in
the parent

class Hewan {
constructor(name) {
this.name = name;
}
class Kucing extends Hewan {
constructor() {
super('Kucing');
}
}
Thank You

You might also like