Skip to content

Latest commit

 

History

History
154 lines (139 loc) · 2.23 KB

File metadata and controls

154 lines (139 loc) · 2.23 KB

JavaScript Array

const name1 = "Jack";
const name2 = "Sarah";
const name3 = "Philip";
...
...
...
const name100 = "Amy";

Create an Array

const routine = ['eat', 'sleep'];
console.log(routine);

Output

 [ 'eat', 'sleep' ]

const numbers = [2, 3, 5, 7];
console.log(numbers);

Output

[ 2, 3, 5, 7 ]

const arr = ['eat', 'sleep', 3, 5, 'run'];
console.log(arr);

Output

[ 'eat', 'sleep', 3, 5, 'run' ]

Access Elements of an Array

const myArray = ['h', 'e', 'l', 'l', 'o'];
console.log(myArray[0]);

Output

h

const myArray = ['h', 'e', 'l', 'l', 'o'];
console.log(myArray[0]);
console.log(myArray[1]);
console.log(myArray[2]);

Output

h
e
l

Array length

const routine = [ 'eat', 'sleep'];
console.log(routine.length);

Output

2

Add an Element to an Array

let routine = ['eat', 'sleep'];

// add an element at the end
routine.push('exercise');
console.log(routine);

Output

['eat', 'sleep', 'exercise']

Change the Elements of an Array

let routine = ['eat', 'sleep'];

routine[1] = 'exercise';
console.log(routine);

Output

[ 'eat', 'exercise' ]

Remove an Element from an Array

let routine = ['work', 'eat', 'sleep', 'exercise'];

// remove the last element
routine.pop();
console.log(routine);

Output

['work', 'eat', 'sleep']

Programming Task

Create an array named greet with values 'hello', 'hi'. Find the length of an array. Add the new element 'welcome' to the array. Find the new length of an array.

Solution:

const greet = ['hello', 'hi'];
const greetLength = greet.length;
console.log(greetLength);
greet.push('welcome');
const addGreetLength = greet.length;
console.log(addGreetLength);

Output

2
3

Programiz Quiz

Q. What is the output of the program?

let routine = [ 'eat', 'sleep'];
routine.push('exercise');
routine[4] = 'work';
console.log(routine[3]);
  1. Error
  2. exercise
  3. undefined
  4. work

Answer: 3