DEV Community

Odegi Christine
Odegi Christine

Posted on

Ultimate Guide to JavaScript

Arrays

An array is a collection of elements. Arrays are a way to store groups of related data inside a single variable.
Arrays are objects and can store any type of data. Arrays are zero indexed, that is, the first element in an array has an index of 0.

Creating arrays

Using new keyword
var studentName = new Array("Mary", "Daniel")

Array literal notation
var studentName = Array.of("Mary", "Daniel")

Array literal
Use of square brackets
var studentName = ["Mary", "Daniel"]

Working with arrays

Adding a new item
Use push method: studentName.push("Stacy")

Removing an item from the list
To remove from the end: studentName.pop()
To remove from the beginning: studentName.shift()
To remove multiple items from the end of an array:

const fruits = ["apple", "orange", "guava"];
const start = -3;
const removedItems = fruits.splice(start)
Enter fullscreen mode Exit fullscreen mode

Joining two or more arrays
Use concat() method

const a = [1,2]
const b = [3,4]
const c = a.concat(b)
Enter fullscreen mode Exit fullscreen mode

Finding items in an array
Use find() method

a.find(element, index, array)
Enter fullscreen mode Exit fullscreen mode

Populating arrays
You can create an empty array and add elements to it later. In order to add elements to an array, specify the index number of the element you want to create or modify

var studentName = [];
studentName[0] = "Lynn";
studentName[1] = "Bryan";
studentName[87] = "Omolo"; //addition does not have to be sequential
Enter fullscreen mode Exit fullscreen mode

Multidimensional arrays
Multiple arrays can be stored in a single array.
An array containing an array is called a multidimensional array. To write a multidimensional array, you add more sets of square brackets to a variable name. e.g:
var ListOfLists [0][0];

Accessing array elements
Use the index number in square brackets.
myArray[2]; //returns third element in the array

To access elements in a multidimensional array, add more square brackets with the index of the element.
var ListOfLists [0][0];

String object

Also known as a string literal and is enclosed in quotes/double quotes.
A string is a sequence of characters.

Creating strings

  1. As primitives, i.e from string literals
    const name= "Christine";

  2. As objects
    const name= newString("Christine");

Character access

  1. charAt() method
    'cat'.charAt(1) //gives value 'a'

  2. Treating the string as ana array-like object, where individual characters correspond to a numerical index.
    'cat'[1] //gives value 'a'

Determining the length of a string using length property

'Fabian'.length //6
const name= 'Fabian'
name.length //6
Enter fullscreen mode Exit fullscreen mode

JavaScript loops

While loop
We add a condition after the while keyword and a block of code that is run until condition evaluates to false.

while (n<3){
    //statements
}
Enter fullscreen mode Exit fullscreen mode

do...while loop
Similar to while except that the condition is evaluated after code block is executed.
The block is always executed at least once.

do{
  //statements
}while (condition)
Enter fullscreen mode Exit fullscreen mode

For loop
Uses the for keyword then passes three instructions: initialization, condition, increment part.

for (i=0; i>10; i++){
    //statements
}
Enter fullscreen mode Exit fullscreen mode

For of loop
Developed in 2015. It is a simplified version of for loop.

const list= ['a', 'b', 'c']
for (const value of list){
console.log(value) //value
}
Enter fullscreen mode Exit fullscreen mode

Objects

An object is any value not of primitive type(string, number, boolean, symbol, null, undefined).

Creating objects

  1. Using object initializers or object literals.
    const car= {}

  2. Using constructor function

  • Define the object type using a constructor function. Use a capital letter.
  • Create an instance of the object using new.
function Student(name, regNumber, course){
        this.name = name,
        this.regNumber = regNumber,
        this.course = course
}
const student1 = new Student ("Christine", "SCT211", "B.Sc Computer Science")
Enter fullscreen mode Exit fullscreen mode

The order of arguments and parameters should be the same. student1.name is assigned "Christine".
You can add a property to a previously defined object.
student1.age = 22;

An object can have a property that is another object.
const object = new Object("value1", "value2", object2)

To access a property in object 2:
object.object2.property

  1. Using the Object.create method to create an object from a prototype.
//create an Animal object
var Animal={
   legs: 2,
   type: "mammal",
}
//create a cat object, based on animal.
var cat = Object.create(Animal)
cat.legs=4;
cat.type= "mammal';
Enter fullscreen mode Exit fullscreen mode

Objects and properties
Objects have properties associated with them.

Accessing properties
Dot notation
student1.name = "Christine";
Bracket notation
student1["name"]="Christine";

You cannot use dot notation to access a property whose name is not a valid JavaScript identifier.
For example, a property name that has a space/hyphen, starts with a number or is held inside a variable can only be accessed using bracket notation.
Examples

const myObj = {};
const str = "myString";
const rand = Math.random();
const anotherObj = {};
//create additional properties on myObj
myObj.type = "value1";
myObj["date created"] = "value2"; //key has space
myObj[str] = "value3"; //the key is in a variable str
myObj[rand] = "value4"; //a random number is the key
myObj[anotherObj] = "value5"; //the key is object anotherObj
myobj[" "] = "value6"; //key is an empty string
Enter fullscreen mode Exit fullscreen mode

Deleting properties
Properties can be deleted from objects using delete operator.

var myObject={
   var1:"value1",
   var2:"value2",
   var3:"value3"
};
//delete var2 from Object
delete myObject.var2
Enter fullscreen mode Exit fullscreen mode

Inheritance
An object can extend another object.

var Person = new Object();
var Val= new Person();
Enter fullscreen mode Exit fullscreen mode

Defining methods
A method is a function associated with an object.

var Car={
   make:"",
   year:"",
   myCar: function(make, year){
        car.make = make;
        car.year = year;
   }
}
//To call the function;
car.myCar("Ford", 1969);
Enter fullscreen mode Exit fullscreen mode

Using this for object references
JavaScript has a special keyword, this, that you can use within a method to refer to the current object.

var Car = {
   make:"",
   year:"",
   myCar: function(make, year){
       this.make = make;
       this.year = year;
   }
}
Enter fullscreen mode Exit fullscreen mode

Classes

Are a way to define a common pattern for multiple objects.
Name of the class starts with a capital letter.

class Person{
     name
}
const john = new Person();
//john is an instance of the Person class

john.name = "John"  //set value of a property
Enter fullscreen mode Exit fullscreen mode

Constructor() is a special method used to initialise class properties when a new object instance is created. I can only be used once in a class.
A constructor can use the 'super' keyword to call the constructor of the super class.

class Person{
    constructor(name){
        this.name= name;
    }
    hello(){
       return 'Hello, I am '+this.name+'.';
    }
}
Enter fullscreen mode Exit fullscreen mode

Method are defined on the object instance, not on the class.
To execute a method on the class, you define it as static.

class Person{
    static genericHello(){
        return 'Hello';
    }
}
Enter fullscreen mode Exit fullscreen mode

Static properties and methods are called without instantiating their class and cannot be called through a class instance.

Inheritance
A class can extend another class and objects initialised using that class.
It can also inherit all the methods of both classes.
Suppose we have class Person, we can define a new class Programmer that extends Person.
If we instantiate a new object with class Programmer, it has access to the hello() method
You can reference the parent class in the child class by calling super()

class Programmer extends Person{
     hello(){
        return super.hello() + '. I am also a programmer.';
     }
}
const flavio = new Programmer();
flavio.hello()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)