Learning a New Language (ft. JavaScript)

Winston Chen
7 min readJan 29, 2021
Photo by Chris Ried on Unsplash

My journey to becoming a software engineer started with Ruby, but what exactly is Ruby? Ruby is a dynamic, open source programming language with a focus on simplicity and productivity. This simplicity allowed me as a beginner to really understand the fundamentals of coding. It wasn’t too difficult to learn since it offers an elegant syntax that is natural to read and easy to write. Ruby sort of served as my training wheels through these past few weeks and months.

However, sooner or later, you have to learn a new language as a programmer. For me, that language was JavaScript. This is where it gets tricky. At first, I thought it would be a much easier transition from one language to another. Oh how I was wrong.. it was super challenging and felt like I was back at square one. Most of it was due to syntax, but also as a learner, I just wasn’t ready to learn a new language in such a short time span.

It’s important as a programmer to focus on the big picture things and you will see just how languages resemble each other and have similar styles, just different flavors.

JavaScript, specifically, is a high level, interpreted programming language. There is a lot of abstraction meaning that you don’t have to deal with things like memory management. It isn’t like a low-level language such as C or C++. Additionally, it is a scripting language and is interpreted. Lastly, Javascript comforms to the ECMAScript specification.

Side note: Java is a completely different language that is unrelated to JavaScript

As someone that had trouble with the syntax and fundamentals of the language, I decided to create a general review of what I’ve learned and found important as I learned JavaScript. Let’s begin…

Here are some things that you can do with a string:

const s = 'Hello World';
console.log(s.length);
console.log(s.toUpperCase());
console.log(s.toLowerCase());
console.log(s.substring(0, 5));
console.log(s.substring(o, 5).toUpperCase());

A method is basically a function that is associated with an object and it need parenthesis.

We can also split a string into an array:

const s = 'Hello World!';console.log(s.split(' '));const s = 'technology, computers, it, code';console.log(s.split(', '));

Arrays:

// Arrays - variables that hold multiple values/* multi
line
comment */
const numbers = new Array(1,2,3,4,5);
const fruits = ['apples', 'oranges', 'pears'];
console.log(numbers);

New keyword and then something after it is telling us that it is a constructor, so we’re contructing an array in the above example..

Now, in JavaScript, you can have multiple data types within the same array so I could put a number, boolean, etc. In a lot of languages, you have to have the same data types in your array. Javascript is not statically typed.

Now, let’s take a look at common methods for arrays…

What if we just wanted to access just one of the fruit:

const fruits = ['apples', 'oranges', 'pears'];console.log(fruits[1]);

Arrays are always zero-based in every language.

How to add on to the fruits array:

const fruits = ['apples', 'oranges', 'pears'];fruits[3] = 'grapes';fruits.push('mangos'); (better way than above)fruits.unshift('strawberries'); (to add to beginning)fruits.pop(); (to take off last one in array)console.log(Array.isArray(fruits)); (to check if something is an array)console.log(fruits.indexOf('oranges'));console.log(fruits);

This is the basis for arrays but there are a lot of other methods.

Next, let’s move on to object literals with key value pairs…

const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
hobbies: ['music', 'movies', 'sports'],
address: {
street: '50 main st',
city: 'Boston',
state: 'MA'
}
}
console.log(person); - RIGHT WAY
alert(person; - WRONG WAY
console.log(person.firstName, person.lastName);
console.log(person.hobbies[1]);
console.log(person.address.city);
const { firstName, lastName, address: { city }} } = person;
console.log(firstName);
console.log(city);

Can also add properties:

person.email = 'john@gmail.com';
console.log(person);

A lot of the times you’re going to be dealing with arrays of objects —

const todos = [
{
id: 1,
text: 'Take out trash',
isComplete: true
},
{
id: 2,
text: 'Meeting with boss',
isComplete: true
},
{
id: 3,
text: 'Dentist appt',
isComplete: false
}
];
console.log(todos);
console.log(todos[1].text);

JSON is a data format and it’s used a lot within full stack development and is used a lot when dealing with API — sent data to a server you usually send it in JSON format and receive it in JSON format — similar to object literals.

To convert to JSON:

const todos = [
{
id: 1,
text: 'Take out trash',
isComplete: true
},
{
id: 2,
text: 'Meeting with boss',
isComplete: true
},
{
id: 3,
text: 'Dentist appt',
isComplete: false
}
];
const todoJSON = JSON.stringify(todos);
console.log(todoJSON);

The result of this is a JSON string and this is how we would send data to a server.

Now, let’s talk about loops:

//For
for(let i = 0; i <= 10; i++) {
console.log('For Loop Number: ${i}');
}
//While
let i = 0;
while(i < 10) {
console.log('While Loop Number: ${i}');
i++;
}

How to loop through arrays:

const todos = [
{
id: 1,
text: 'Take out trash',
isComplete: true
},
{
id: 2,
text: 'Meeting with boss',
isComplete: true
},
{
id: 3,
text: 'Dentist appt',
isComplete: false
}
];
for(let i = 0; i < todos.length; i++) {
console.log(todos[i].text);
}
This isn't the best way to loop through an array, there are other methods such as a for of loop

Could use length on a string, but can also use on an array.

This isn't the best way to loop through an array, there are other methods such as a for of loop:

const todos = [
{
id: 1,
text: 'Take out trash',
isComplete: true
},
{
id: 2,
text: 'Meeting with boss',
isComplete: true
},
{
id: 3,
text: 'Dentist appt',
isComplete: false
}
];
for(let todo of todos) {
console.log(todo);
}
for(let todo of todos) {
console.log(todo.text);
}
for(let todo of todos) {
console.log(todo.id);
}
*Todo can be anything

There are also high order array methods which is the recommended way to do any kind of iteration with arrays…

forEach:

// forEach, map, filtertodos.forEach(function(todo) {
console.log(todo.text);
});

Map:

const todoText = todos.map(function(todo) {
return todo.text;
});
console.log(todoText);

Filter:

const todoCompleted = todos.filter(function(todo) {
return todo.isCompleted === true
});
console.log(todoCompleted);

Can also chain on other array methods:

const todoCompleted = todos.filter(function(todo) {
return todo.isCompleted === true
}).map(function(todo) {
return todo.text;
})
console.log(todoCompleted);

Very powerful — this is functional programming — you can really manipulate data pretty much however you want — you can do some pretty wild stuff with these array methods

We also have conditionals…

Simple if statements:

const x = 10;if(x == 10) {
console.log('x is 10');
}

Triple equal signs also matches the datatypes

const x = '10';if(x === 10) {
console.log('x is 10');
}

Personal preference: always use triple equal signs

Here is a simple if-else + else if:

const x = 20;if(x === 10) {
console.log('x is 10');
} else {
console.log('x is NOT 10');
}
if(x === 10) {
console.log('x is 10');
} else if(x > 10) {
console.log('x is greater than 10');
} else {
console.log('x is less than 10');
}

Here is a switch:

const x = 9;const color = 'green';switch(color) {
case 'red':
console.log('color is red');
break;
case 'blue':
console.log('color is blue');
break;
default:
console.log('color is NOT red or blue'(;
break;
}

Let’s move on to functions

function addNUmns(num1, num2) {
console.log(num1 + num2);
}
addNums(5,4);

Can set default numbers:

function addNUmns(num1 = 1, num2 = 1) {
console.log(num1 + num2);
}
addNums(5,4);

Can cut things down

const addNums = num1 => num1+ 5;console.log(addNums(5));todos.forEach((todo)) => console.log(todo));

Let’s move on to object oriented programming:

  • Constructor function
// Constructor function
function Person(firstName, lastName, dob) { should be capatilized
this.firstName = firstName;
this.lastName = lastName;
this.dob = dob;
}
// Instantiate object
const person1 = new Person('John', 'Doe', '4-3-1980');
const person2 = new Person('Mary', 'Smith', '3-6-1970');
console.log(person1);
console.log(person2.firstName);

Let’s talk about dates, because we passed in DOB above as a string. However, we can turn this into a date object by using the date constructor:

function Person(firstName, lastName, dob) { should be capatilizedthis.firstName = firstName;
this.lastName = lastName;
this.dob = new Date(dob);
}

When you have a date object, there’s a bunch of methods you can call on it!

So now, we can actually add methods, which are basically just functions, to this person object:

// Constructor function
function Person(firstName, lastName, dob) { should be capatilized
this.firstName = firstName;
this.lastName = lastName;
this.dob = new Date(dob);
this.getBirthYear = function() {
return this.dob.getFullYear();
}
this.getFullName = function() {
return '${this.firstName} ${this.lastName}';
}
}
// Instantiate object
const person1 = new Person('John', 'Doe', '4-3-1980');
const person2 = new Person('Mary', 'Smith', '3-6-1970');
console.log(person1.getBirthYear());
console.log(person1.getFullName());

The above isn’t the best way to do it, so let’s talk about prototypes:

// Constructor function
function Person(firstName, lastName, dob) { should be capatilized
this.firstName = firstName;
this.lastName = lastName;
this.dob = new Date(dob);
}
Person.prototype.getBirthYear = function() {
return this.dob.getFullYear();
}
Person.prototype.getFullName = function() {
return '${this.firstName} ${this.lastName}';
}
// Instantiate object
const person1 = new Person('John', 'Doe', '4-3-1980');
const person2 = new Person('Mary', 'Smith', '3-6-1970');
console.log(person2.getFullName());
console.log(person1.getFullName());

Let’s talk about ES6, which uses classes to make it easier than above:

//Class
class Person {
constructor(firstName, lastName, dob) {
this.firstName = firstName;
this.lastName = lastName;
this.dob = new Date(dob);
}
getBirthYear() {
return this.dob.getFullYear();
}
getFullName() {
return '${this.firstName} ${this.lastName}';
}
}

Do this rather than deal with prototypes, helps if you come from other background.

Now, let’s talk about the DOM:

Manipulating the DOM:

const ul = document.querySelector('.items');ul.remove();
ul.lastElementChild.remove();
ul.firstElementChild().textContent = 'Hello':
ul.children[1].innerText = 'Brad';
ul.lastElementChild.innerHTML = '<h1>Hello</h1>';
const btn - document.querySelector('.btn');
btn.style.background = 'red";
const btn = document.querySelector('.btn');btn.addEventListener('click', (e) => {
e.preventDefault();
document.querySelector('#my-form').style.background = '#ccc';
document.querySelector('body').classList.add('bg-dark');
});
const myForm = document.querySelector('#my-form');
const nameInput = document.querySelector('#name');
const emailInput = document.querySelector('#email');
const msg = document.querySelector('.msg'(;
const userList = document.querySelector('#users');
myForm.addEventListener('submit', onSubmit);function onSubmit(e) {
e.preventDefault();
if(nameInput.value === '' || emailInput.value === '') {
msg.classList.add('error');
msg.innerHTML = 'Please enter all fields';
setTimeout(() => msg.remove(), 3000);
} else {
const li = document.createElement('li');
li.appendChild(document.createTextNode(nameInput.value} :${emailInput.value}'));
userList.appendChild(li); // Clear fields nameInput.value = ''; emailInput.value = '';
}
}

This is a great place to wrap up. We went through some basic syntax and fundamentals that you should be aware of in JavaScript. This is a starting point, but there is still a lot to learn. Good luck on your journey as you start learning a new language!

Photo by Clemens van Lay on Unsplash

--

--

Winston Chen

Full-Stack Web Developer, specializing in React and Ruby on Rails.