loading...
Cover image for The vanilla Javascript basics to know before learning React JS

The vanilla Javascript basics to know before learning React JS

tracycss profile image Jane Tracy ๐Ÿ‘ฉ๐Ÿฝโ€๐Ÿ’ป Updated on ใƒป9 min read

REACT JS

Background Story

If you just finished JavaScript online courses or other self-taught resources going to your first JS framework can be scary. One thing I would like to encourage you is that we all have some doubts as a beginner. But pushing through the 'fear/doubt' of I don't think 'I am ready enough' or 'smart enough' is something that you go through. Coding is a continuous journey that evolves all the time with new programming languages or frameworks being created. If you are presented with an opportunity to be on a project that uses a framework or technology that you haven't used, don't be quick to say no. Just say you don't know it but you are willing and ready to learn it. At least that's what I did. In the next three months, I will be learning React as I contribute to the project, the team, and grow.

Happy gif

Let's get started with the vanilla javascript basics

In the process of learning React JS, I have found a few things you should understand before starting it. I will brush through the features and add useful links to the documentation you can use to learn them on a deep level. These are ES6 syntax or ES7 syntax mostly used are:

  • Es6/ES7 classes
  • Arrow functions
  • let and const
  • Imports and Exports
  • Spread and rest operator
  • Destructuring
  • Array functions especially filter and map

Using Let and Const variables

Before var was used to set new variables but with the ES6 updates let and const were introduced.
Scope: var variables are globally scoped or accessible. This means when they are declared outside a function they are accessible throughout your file or window. This can be dangerous because you can change it without knowing, hence getting a lot of errors. let and const has blocked scope. This means when they are declared inside a function or any block of code, they canโ€™t be accessed outside it. Thus you canโ€™t easily break your code by manipulating or redeclaring the same variable outside the function.
Re-assigning: Var variables can be re-assigned and updated easily, let can be updated but not re-assigned, and const variable can't be re-assigned, it is constant(doesnโ€™t change). But the values within a const array or properties within a const object can be changed.


//Var can be re-assigned
var name = 'Jane Tracy ๐Ÿ‘ฉโ€๐Ÿ’ป';
var name = 'Luke Wilsey ๐ŸŽฅ';
console.log(name);
//output => Luke wilsey ๐ŸŽฅ 

//var can be updated too
var name = 'Spencer ๐Ÿ‘ฉโ€๐Ÿ’ป';
name = 'Tom๐Ÿ„';
console.log(name);
//output => Tom๐Ÿ„

//let canโ€™t be re-assigned
let name = 'Jane Tracy ๐Ÿ‘ฉโ€๐Ÿ’ป';
let name = 'Luke Wilsey ๐ŸŽฅ ';
console.log(name);
//output => Syntax error: the name has already been declared

// let can be updated
let name = 'Spencer ๐Ÿ‘ฉโ€๐Ÿ’ป';
name = 'Tom๐Ÿ„';
console.log(name);
//output => Tom๐Ÿ„

//const canโ€™t be re-assigned
const name = 'Jane Tracy ๐Ÿ‘ฉโ€๐Ÿ’ป';
const name = 'Luke Wilsey ๐ŸŽฅ ';
console.log(name);
//output => Syntax error: the name has already been declared

//const object properties or array values can be changed
const friends = [{
    name: 'Bob ๐Ÿฅฝ',
    age: 22,
    hobby: 'golf๐ŸŒ',
    music: 'rock ๐ŸŽธ'
  }

];

const result = friends.age = 23;
console.log(result);
//output => 23

// const object can't be re-assigned 
const friends = [{
    name: 'Bob ๐Ÿฅฝ',
    age: 22,
    hobby: 'golf๐ŸŒ',
    music: 'rock ๐ŸŽธ'
  }

];

friends = [{
  name: 'Jane ๐Ÿฅฝ',
  age: 24,
  hobby: 'golf๐ŸŒ',
  music: 'Pop ๐ŸŽธ'
}];

console.log(friends);
//output => Uncaught TypeError: Assignment to constant variable.

For more about const take a look at W3Schools section on const

Arrow functions

When I started learning about arrow functions, I immediately loved them. They are short and straight to the point. Basically arrow functions are a way to write functions with shorter syntax. They were also introduced in the ES6 update.

  • Named functions without arguments

//old function syntax 
function name() {
  console.log("Tracy ๐Ÿš ");
}
name();

// arrow function
const name = () => {
  console.log("Tracy ๐Ÿš ");
};
name();
//or you can even make it shorter by removing writing

const name = () => console.log("Tracy ๐Ÿš ");
name();

Named functions with arguments

function add(a, b) {
  return a + b;
}
console.log(add(3, 5));

//arrow function
const add = (a, b) => {
  return a + b;
};
console.log(add(3, 5));

//you can also shorten if it returns one thing
const add = (a, b) => a + b;
console.log(add(3, 5));

  • Not using parentheses when you have one argument
//Using template literals to avoid the old concatenation
const series = favorite => console.log(`I love watching ${favorite}`);
series("The office");

Note: Arrow functions are used a lot in modern frameworks, it will be better if you get comfortable with them. For a deep dive look at Arrow functions by MDN

ES6 Classes

A class is another type of function which is declared by the class keyword and can be used to create new objects. A class contains properties and methods. The constructor method is used for initializing objects that are created by the class itself and we use this keyword to refer to the current class.

class GreatMovies {
  constructor(movie) {
    this.movie = "The Lord of the Rings ๐ŸŽฅ";
  } 

  printMovie(){
    console.log(`My favorite movie is ${this.movie}`);
  };
}

//this creates an object by using new before the class name
const myMovies = new GreatMovies(); 
myMovies.printMovie();
//output => My favorite movie is The Lord of the Rings ๐ŸŽฅ

Class inheritance

We use extends in classes to inherit properties from another class.
In the example below, the class GreatSeries inherits the property and method from the GreatMovies class. The super method is used to call the parent constructor. In our case, it will call the constructor of the GreatMovies class.

class GreatMovies {
  constructor(movie) {
    this.movie = movie;
  }

  printMovie() {
    return `My favorite movie is ${this.movie}`;
  }
}

class GreatSeries extends GreatMovies {
  constructor(movie, series) {
    super(movie);
    this.series = series;
  }

  printList() {
    return `${this.printMovie()}, now I am watching ${
      this.series
    } series today.`;
  }
}
const watchingList = new GreatSeries("The Social dilemma", "The Society");
console.log(watchingList.printList());


ES7 class syntax

The best thing about the ES7 class syntax you donโ€™t have to write the constructor or the super method. We can also use the arrow functions as class methods. This for me makes it easier and faster to write code.
Let's redo the former classes we used and change it to ES7 syntax.

class GreatMovies {
  movie = "The Social dilemma";

  printMovie = () => {
    console.log(`My favorite movie is ${this.movie}`);
  };
}

const myMovies = new GreatMovies();
myMovies.printMovie();

es7-syntax

How to write extended classes without the super method

The constructor and super method are written behind the scenes, so you donโ€™t have to write them.

class GreatMovies {
  movie = "The Social dilemma";

  printMovie = () => {
    console.log(`My favorite movie is ${this.movie}`);
  };
}

class GreatSeries extends GreatMovies {
  movie = "The Social dilemma ๐ŸŽฅ ";
  series = "The Society";

  printList = () => {
    return `My favorite movie is ${this.movie} and now I am watching ${this.series} series today ๐Ÿน.`;
  };
}

const watchingList = new GreatSeries();
console.log(watchingList);
console.log(watchingList.printList());

For more about classes check out MDN mozilla docs

Imports and exports

You can store functions in one Javascript file and later on export it to use it in another Js file by importing the file or a specific function/s.

How to export a file or some functions
You can use the default when exporting one main thing from the file. This can be done only once in a file.

const movieList = movie => `I enjoyed watching ${movie} movie`;

export default movieList;

//If the function is more than one
const movieList = movie => `I enjoyed watching ${movie} movie ๐Ÿ’• `;

const seriesList = series => `I enjoyed watching ${series} series ๐Ÿน `;

export {movieList , seriesList as default};

//You can also export function individually => named export
export const movieList = (movie) => `I enjoyed watching ${movie} movie ๐Ÿ’• `;

export const seriesList = (series) => `I enjoyed watching ${series} series ๐Ÿน `;



How import files

//How to import multiple functions individually
//uses the named export
import {movieList, seriesList} from './watching/mylist.js';

//how to import one function called movieList
//using the default export
import movieList from './watching/mylist.js';

//importing using an alias
import {movieList as MovieList} from "./watching/mylist.js";


If you want to learn more about imports and exports you can follow the following resources
import and export in Javascript by Digital Ocean
import and export by Javascript info

Spread and rest operator

When I first heard of this operator I was so curious to understand how only three dots can be so powerful, simple and easy to use. To me the three dots were like magic, a safe way to copy reference types without any issues.
The spread and rest operator uses three dots (. . .) to initialize it.
The spread operator is used for splitting up the values of an array and adding them to another array or splitting the properties of an object and adding them to another object.

//In arrays
const jobs = ["teacher ๐Ÿ‘ฉโ€๐Ÿซ ", "engineer ๐Ÿงฐ", "developer ๐Ÿ‘ฉโ€๐Ÿ’ป"];

const currentJobs = [
  ...jobs,
  "actor ๐ŸŽฅ",
  "social media influencer ๐Ÿ“ด",
  "musician ๐ŸŽป",
];

console.log(currentJobs);
//output => ["teacher ๐Ÿ‘ฉโ€๐Ÿซ ", "engineer ๐Ÿงฐ", "developer ๐Ÿ‘ฉโ€๐Ÿ’ป", "actor ๐ŸŽฅ", "social media influencer ๐Ÿ“ด", "musician ๐ŸŽป"]

//In objects
const currentJob = {
  name: "Jane",
  job: "developer ๐Ÿ‘ฉโ€๐Ÿ’ป",
};

console.log(currentJob);

const funJob = {
  ...currentJob,
  name: "Tracy",
  PartTimejob: "musician ๐ŸŽป",
};

console.log(funJob);
//output => {name: "Tracy", job: "developer ๐Ÿ‘ฉโ€๐Ÿ’ป", PartTimejob: "musician ๐ŸŽป"}

The rest operator
This operator is used to represent an infinite amount to arguments in a function.

const num = (...args) => {
  return args.map((arg) => arg / 2);
};
const result = num(40, 60, 80, 120, 200, 300);
console.log(result);

//output => [20, 30, 40, 60, 100, 150]

//example 2
const myFruits = (...fruits) => {
  return fruits.filter((fruit) => fruit !== "๐ŸŒ");
};

const result = myFruits("๐ŸŽ", "๐Ÿฅ", "๐ŸŒ", "๐Ÿ", "๐Ÿ‰", "๐Ÿ");

console.log(result);
//output
["๐ŸŽ", "๐Ÿฅ", "๐Ÿ", "๐Ÿ‰", "๐Ÿ"]


Destructuring

At first I thought that destructuring and the spread operator do the same job, but I was wrong. The spread operator copies all the values of an array or all properties of an object while destructuring copies specific values or properties which you store in a variable.
Array destructuring

const myFruits = ["๐ŸŽ", "๐Ÿฅ", "๐ŸŒ", "๐Ÿ", "๐Ÿ‰", "๐Ÿ"];
const [myFavorite, , , listFavorite] = myfruits;
console.log(myFavorite, listFavorite);
//output 
๐ŸŽ ๐Ÿ

Objects destructuring

const { name, job } = { name: "Tracy", job: "musician ๐ŸŽป" };
console.log(name, job);
//output 
Tracy musician ๐ŸŽป

Array function

Array functions are not new but they are still important to know and practice on. In react, map and filter methods are commonly used when dealing with data. For more about them, go to the MDN docs, it's my best resource to learn about Js array functions.

Filter method
The filter method creates a new array of elements that returned true from the call back function passed.

const friends =[
  {name: 'Jane', age: 23},
  {name: 'Bob', age: 22},
  {name: 'Tracy', age: 24},
  {name: 'Jack', age: 25},
  {name: 'Fred', age: 25}
];

const filterAge = friends.filter(friend => friend.age> 23);
console.log(filterAge);
//output 
 [
  {name: 'Tracy', age: 24},
  {name: 'Jack', age: 25},
  {name: 'Fred', age: 25}

 ]

In the example above it returns the objects with people who are 23 years and above only.

Map method
The map method creates a new array from the results of the callback function. The callback is called on each index on the array. The indexes are the elements in the array. Letโ€™s look at an example.

const friends = [{
    name: 'Jane ๐ŸŒŸ',
    age: 23
  },
  {
    name: 'Bob ๐Ÿฅฝ',
    age: 22
  },
  {
    name: 'Tracy ๐ŸŒ',
    age: 24
  },
  {
    name: 'Jack ๐ŸŽธ',
    age: 25
  },
  {
    name: 'Fred ๐Ÿคพ',
    age: 25
  }
];
const mapNames = friends.map(friend => friend.name);
console.log(mapNames);

//output
["Jane ๐ŸŒŸ", "Bob ๐Ÿฅฝ", "Tracy ๐ŸŒ", "Jack ๐ŸŽธ", "Fred ๐Ÿคพ"]

Where to learn React for free

Learn react for free by Bob ziroll in scrimba
FreeCodeCamp react and redux section
Front end development with React in Coursera
Building application with react and flux by Cory House from PluralSight

In conclusion

To make your transition to react learn Javascript first, donโ€™t rush the course or documentation. Take your time weeks or months to ensure you understand vanilla Javascript. When I started with Javascript three months ago, I never thought I could even explain Js this well. Kinda laughing at myself since I thought I would take a year or so to understand mid-level JS ๐Ÿฅบ(Hey, don't laugh at me ๐Ÿ˜„). I hope this article gives you an idea of the topics I brushed through. For more details and in-depth look, check out MDN Docs. For learning about ES6, ES7, ES8, ES9 see history of Javascript article by Madasamy M

If you find this post useful share it with your peers or beginners who learning Javascript and want to react js. You can also buy me coffee. ๐Ÿ™‚

Buy Me A Coffee

xo xo gif

Posted on by:

tracycss profile

Jane Tracy ๐Ÿ‘ฉ๐Ÿฝโ€๐Ÿ’ป

@tracycss

I am a User Interface Designer learning web development. I don't know what I am doing but I am trying my best to grow as a self taught developer. Welcome to my newbie tech journey.๐Ÿ‘ฉโ€๐Ÿ’ป

Discussion

pic
Editor guide
 

const can neither be re-assigned nor updated, it is constant(doesnโ€™t change).

I think that is a little misleading. The reference is constant, the object is not; fields can be reassigned and added.

const x = { y: 'x is const' };
x.y = 'y is not';
x.a = 'here is a new property';
console.log(x.y); // y is not
console.log(x.a); // here is a new property
delete x.y;
console.log(x.y);  // undefined
Enter fullscreen mode Exit fullscreen mode

Colloquially, those are all updates.

 

You can not reassign an object or an array but you can still change the values or properties.
Let me change the text a little.
Thanks for pointing this out Robert, yeahhhh :)

 

@tracycss thank you for the great article :)

This snippet

//const object properties or array values can be updated
const friends = [{
    name: 'Bob ๐Ÿฅฝ',
    age: 22,
    hobby: 'golf๐ŸŒ',
    music: 'rock ๐ŸŽธ'
  }

];

const result = friends.age = 23;
console.log(result);
//output => 23

does not update the original age (I guess the code was intended to update age from 22 to 23, right?). Instead it creates a new named property of the array object:

console.log(friends);
[
  { name: 'Bob ๐Ÿฅฝ', age: 22, hobby: 'golf๐ŸŒ', music: 'rock ๐ŸŽธ' },
  age: 23
]

This can be checked:

// new (named) age property
console.log(friends.age);
23
// also
console.log(friends["age"]) ;
23

// original age
console.log(friends[0].age) ;
22

To update the original age:

friends[0].age = 23;
console.log(friends[0].age) ;
23
// also
console.log(friends[0]["age"]) ;
23
 

Great input Max, I might the values or properties can be changed. Let me update that part.
Thank you. ๐Ÿ’ฏ๐ŸŒŸ๐Ÿ™‚

 

We can also use the arrow functions as class methods.

Despite of what you may see in framework tutorials in terms of "Vanilla JS" that is considered bad form.

The issue is that in arrow functions this refers to the lexical scope that created the function.

As a consequence each object instance will create a new, separate function.

For a regular method a single function exists on the prototype object of all the object instances that share it - i.e. one single function is reused across all object instances. For traditional methods (including the short hand syntax) this (the function context) refers to the calling context.

So when using arrow functions for "regular methods" you are creating more functions than you need to.

Arrow functions in class declarations are justified when that function is intended to be used as a callback (e.g. event listener), i.e. it needs to be bound to (this of) that particular object instance.

Please have a look at:

Also ES6 is the legacy term for ES2015. There is no ES7. Since ES2015 TC39 has annually published updates to the spec, e.g. ES2016, ES2017, etc.

The additions (finished proposals) for each publication year are identified here.

Some people use "ES.Next" when Babel offers implementations of proposals before they reach stage 4 (finished).

var variables are globally scoped or accessible.

Inside a function they are scoped to the function - i.e. not globally accessible - that is what the "immediately invoked function expressions" IIFE are about. However var declarations are effectively hoisted to the top of the function - independent of where they appear inside the function.

A class is another type of function

There is a class declaration and class expression.

The MDN's statement:

Classes are in fact "special functions"

is a bit misleading. It's more accurate to say that classes are syntax sugar for constructor functions.

we use this keyword to refer to the current class.

"we use this keyword to refer to the current object (an instance of the class)."

And as already mentioned this has a different meaning in arrow and traditional methods:

  • arrow function - the object the function was created on
  • traditional method - the object the method is called on

The super method

super is a keyword. super([arguments]) is only valid in the constructor. super.name or super[name]can be used to access properties (and functions/methods) on the parent.

The spread operator is used for splitting up the values of an array

The spread syntax also works on object literals and can also be used to convert an iterable to arguments for a function call.

JSX supports spread attributes:

function App1() {
  return <Greeting firstName="Ben" lastName="Hector" />;
}

function App2() {
  const props = {firstName: 'Ben', lastName: 'Hector'};
  return <Greeting {...props} />;
}
Enter fullscreen mode Exit fullscreen mode

This operator is used to represent an infinite amount to arguments in a function.

Some people think of the rest syntax as "gather" because it collects the remaining arguments.

The rest syntax can also be used for Array destructuring and Object destructuring.

You can use "rest in object destructuring" to omit object properties.

let {b, c, ...redacted} = {a: 4, b: 3, c: 2, d: 1};
console.log(redacted); // {a: 4, d: 1}
Enter fullscreen mode Exit fullscreen mode

Array functions

One issue is that these functions are limited to arrays rather than general iterables. While at times Array.from, Object.entries, Object.keys, and Object.values can be helpful often it's more performant to stick to using for..of.

 
 

ECMA-262 7แต—สฐ Edition / June 2016 => ECMAScriptยฎ 2016 Language Specification

Edit:
When the "Standard ECMA-262 6th Edition" was being drafted it was referred to as ES6.

However before it was finalized the committee decided to go with the ES2015 moniker to reflect the fact that they intended to publish yearly updates to the specification - which they have done so far.

Publications before June 2015 can be excused for using the ES6 moniker, past that ES2015 should have been used.

It's been 5 years - it's time to let go of the edition based moniker unless one is referring to ES5.1 and below.

Cool...Ill keep this in mind while writing configs that use ES5-11 but hey you do you.

 
 

Great input, I will take a look at the links.

 

Good coverage for three months ๐Ÿ‘

Edit:
Method vs "arrow function on public class field" weirdness:

class A {
  myArrow = () => {
    console.log('A.myArrow()');
  }

  myMethod() {
    console.log('A.myMethod()');
  }
}

class B extends A {
  myArrow = () => {
    super.myArrow(); // arrow function exists on 
                     // public class field of A but
                     // but is not available on 
                     // the prototype chain via `super`
    console.log('B.myArrow()');
  }

  myMix() {
    super.myArrow(); // same problem
    console.log('B.myMix()');
  }

  myMethod() {
    super.myMethod(); // just works
    console.log('B.myMethod()');
  }
} 

let myB = new B();

myB.myMethod(); // 'A.myMethod()'
                // 'B.myMethod()'
myB.myMix();    // Uncaught TypeError: (intermediate value).myArrow is not a function at B.myMix
myB.myArrow();  // Uncaught TypeError: (intermediate value).myArrow is not a function at B.myArrow

Awesome, explanation. ๐Ÿ™‚๐ŸŒŸ

 

In Netscape era, I could read the entire JavaScript specification.
In ES5 times, the paper book for ECMA-262 standard is still reasonable thickness. I have the book from 2011 and it's 245 pages. (the book is free and they'll mail it to you if you request)
Nowadays, JavaScript is so complicated. I read all of MDN but there must be more.

P.S. I prefer chocolate to vanilla.

 

I would be interested to have a look at the book. You can email me, I appreciate it :)

 

It's okay. My email is janetracy00@gmail.com.
I will go through it slowly taking my time. No rush :)

 

Very useful guide ๐Ÿ˜€! A lot of people are curious about when to start learning react. Thx for sharing ๐Ÿค—

 

Thank you. Glad you enjoyed it. ๐Ÿ˜๐Ÿ™Œ
I hope it helps in any way, don't forget to share to help some else out there.โœจ

 

I will ๐Ÿ˜๐Ÿ‘!!

 

Thank you for this! I especially like your description of variables (let/const) and arrow functions. I needed that.

 

I am glad the information was useful. ๐ŸŒŸ๐Ÿ’ฏ
Thank you for reading it, Christopher. ๐Ÿ™Œ๐Ÿฝ

 

Hi Jane, great article. I think you really nailed some of the key JS concepts that should be learned before React! Thanks for the article!

 

Thank you, Cierra. Glad you found it helpful. โœ”โœจ

 

This was really helpful, thanks ๐Ÿ‘

 

Glad it was helpful in any way, Chris. โœจ

 

Wow, really amazing post - thank you

How much time you need for one like this post, there is so much valuable information and very clearly to understand it!

 

I a lot of time. But I take breaks and code in between as well. I can't clearly know how much time I use continuously to write it. But if I would make a guess, it would be a min of 6 hours.

Thank you. Hope it helped in any way, Derva :)

 

good one. I appreciate it.

 
 

Really nice, polished and concrete article. I really enjoyed reading it ๐Ÿ˜„๐Ÿค“

 

Thank you so much, Yuriy. I really appreciate it. โคโœจ

 

Good article best to know javascript better before jumping into a framework like React. Too many beginners make that mistake.

 

thanks ! it was really helpful for me! probably next month i'm going to start with React

 

I am happy the post will guide you or help you in any way. Don't forget to share with your fellow devs, they might find it useful too :)

 

Please add Computed Property ,if you can
ref : ui.dev/computed-property-names/
And also add shallow copy & deep copy concept, Reference type vs value type.
Thanks!!

 

Thanks, Harshil, I will do an update on the post :)