02 JS
02 JS
Objects
1
Js Objects
const person = {
name: "cumar", // property
age: 25, // property
getDetails: function () { // method
console.log('My name is ' + this.name;
}
}
2
Object types
3
Getting object types
const str = "hello"
const num = 10
const tf = true
const obj = { name: 'cali' }
4
Strings
5
Strings
• Zero or more characters written inside quotes.
– single or double quotes:
const name = "cali"
const name = 'axmed'
const sentence = "I'm student"
6
Escaping characters
• Single quote
const sentence = 'I \'m student'
• Single quote
const sentence = "I \"m student"
• Single quote
const sentence = 'I \\m student'
7
String methods
• Length: get length of string
const text = "I am coder"
const coder = text.length // 10
8
String methods
• Substring: similar to slice(). The difference is that the
second parameter specifies the length of the
extracted part.
const text = "I am coder"
const coder = text.substr(5, 4) // code
10
String methods
• trim: removes whitespace from the [left, right] sides
of a string.
const text = " I am coder "
// I AM CODER
const coder = text.trim()
13
Number methods
• toString: returns a number as a string.
const figure = 10
console.log(figure.toString()) // "10"
14
Number methods
• Number: used to convert [numeric] string variables
to numbers.
const figure = "10.5465"
console.log(Number(figure)) // 10.5465
15
Arrays
16
Array methods
• Length: property returns the length (size) of an array.
const list = [1, 2, 3, 4]
list.length // 4
17
Array methods
• push: adds a new element to an array (at the end).
const list = [1, 2, 3, 4]
list.push(5) // [1, 2, 3, 4, 5]
18
Array methods
• shift: removes the first array element and "shifts" all
other elements to a lower index.
const list = [1, 2, 3, 4]
list.shift() // [2, 3, 4]
19
Array methods
• sort: sorts an array alphabetically/numerically.
const list = ["xasan", "cali", "maxamed"]
list.sort() // ['cali', 'maxamed', 'xasan']
20
Array methods
• indexOf: searches an array for an element value and
returns its position [first occurrence] otherwise -1.
const list = ["xasan", "cali", "maxamed"]
list.indexOf("cali") // 1
21