JavaScript Basics | Syntax cover image

JavaScript Basics | Syntax

Jonathan Barrios • September 2, 2020

javascript

Introduction

Welcome to the JavaScript Basics series for beginners. In Part 2, we'll focus on JavaScript syntax, from semicolons and identifiers to variables and string literals. See you there!

Prerequisites

To get the most out of this course, you should know:

In Part 2 of JavaScript Basics, we'll focus on:

In future JavaScript Basics posts, we will:

Note: It takes years of focused practice to become a great JavaScript engineer. This JavaScript Basics course is an introduction to JavaScript fundamentals and will improve your coding skills, but don't expect to transform into a JavaScript expert overnight instantly. Remember, the JavaScript learning journey is a marathon, not a sprint.

Semicolons

Interestingly enough, semicolons are optional in JavaScript as the interpreter adds them for you. I prefer not to use semicolons in my code, but many people do. I'm using the Prettier extension, so I can have semicolons removed on each save, it's sort of great. We'll discuss Prettier and ESLint later in the course.

Whitespace

Whitespace is not meaningful in JavaScript like it is in Python. Again, I use the Prettier extension, so I don't worry about whitespace much. It's a best practice to ignore that whitespace is not meaningful and write code according to style guides such as the AirbnB JavaScript Style Guide, or you use something like the Prettier extension, and ESLint configured with a style guide.

Identifiers

An identifier is a sequence of characters used to identify variables, functions, and objects. Identifier first characters must start with a letter, $ dollar sign, _ underscore, and can include integers.

var name = 'Jonathan'
var name2 = 'Jonathan'
var _joanthan_codes = 'Jonathan Barrios'

Case Sensitive

JavaScript is case sensitive, so List and list are not the same, which is also true for any identifier.

Literals

What is a literal? Literals represent values in JavaScript––literally. For example, a string literal is zero or more characters enclosed in 'single' or "double" quotes. We also have number literals, such as 5 or 5000. We'll cover object literals and array literals and more later in the course.

Comments

Comments in Javascript are either two forward slashes for single-line comments or slash asterisk for multiline comments, as described below:

// single line comment

/*
Multiline
comment ✌🏼
*/

Variables introduction

We'll get into variables later in the course but now think of variables as placeholder names to store data. There are three keywords used for variable declarations, var, let, and const which we'll discuss soon; for now, let's use the older var keyword with this line of code:

var name = 'Jonathan'

I used quotes for the name because the text Jonathan is a string, as denoted by quotes. They can be single or double quotes, and we'll explorer those differences later in the course.

var name = Jonathan

If you don't use single or double quotes, you'll get ReferenceError: jonathan is not defined because the JavaScript interpreter doesn't know Jonathan is a string, which is why we use quotes. Semicolons mark the end of a line, and again, we'll cover strings, variables, and more later in the course, but it's worth noting the rules for naming variables:

Try writing some variables yourself, and don't be afraid to intentionally write code to test for errors. Up next, numbers and simple math with JavaScript.

Numbers and Math

Operators, numbers, and math allow us to combine simple expressions into core complex expressions. Try the following examples in the JavaScript console or Visual Studio Code's integrated terminal.

// Variables
var num_a = 100
var num_b = 22

// Simple math operations:

// Addition
value = num_a + num_b
console.log(value)

// Substraction
value = num_a - num_b
console.log(value)

// Division
value = num_a / num_b
console.log(value)

// Multiplication
value = num_a * num_b
console.log(value)

// Modulo
value = num_a % num_b
console.log(value)

Strings and Concatenation

As we discovered earlier, a string is an object of type String whose value is text. To communicate that the data type we're using is a string, you must use quotes. Single and double quotes behave the same, except when escaping itself. Escaping is needed when you have three single or double quotes in one string literal or maybe you're using more than three single or double quotes; both return errors and require escaping to work as intended. To avoid this, you can use a \ or use the other quote not being used. For example:

// Without escaping
var chatbot = 'I'm not human.';
// With escaping
var chatbot = "I'm not human."

// or

var chatbot = "I'm not human."

I prefer the other quote escape over the \, but feel free to use whichever you prefer. To help you remember, think: “Double quotes ‘escape’ double quotes“. Template literals allow us to escape strings and so much more, but first, let's dive into concatenation and string methods. In the next sections, we'll dive into strings, concatenation, and template literals.

We can connect or concatenate two or more string literals. We can join the first and last names from two variables: f_name and l_name. We can use string literals to add space and even a message.

var f_name = 'Jonathan'
var l_name = 'Barrios'

var value
// Concatenation
value = f_name + l_name
console.log(value)
// Add space this way
value = f_name + ' ' + l_name
console.log(value)
// Add space like this as well
value = 'Hello, my name is ' + f_name
console.log(value)

// Append shortcut
value = 'Jonathan '
console.log(value)
// Shorthand notation
value += 'Barrios'
console.log(value)

String Methods

String Methods are built-in functions we can use to manipulate strings. We'll go into methods in more detail when discussing Objects later in the course.

// Length
value = f_name.length
console.log(value)

// Concat
value = f_name.concat(' ', f_name)
console.log(value)

// Case
value = f_name.toLowerCase()
console.log(value)
value = f_name.toUpperCase()
console.log(value)

// IndexOf()
value = f_name.indexOf('j')

// charAt()
value = f_name.charAt('2')

// Slice()
value = f_name.slice(0, 3)
value = f_name.slice(-3)

// Split()
longString = 'I like to dance on the moon'
value = longString.split(' ')
console.log(value)

Template Literals

Template literals are part of ES6 and work on all modern browsers and come in handy. For example, imagine you want to return 'Here's Johnny!' which will return an error because one of the three single quotes expects a single closing quote. In this case, you can use double quotes to return "Here's Johnny". Additionally, there are times when you can use template literals to make code more readable and easier to write:

const name = 'Jonathan'
const title = 'web developer'
const city = 'Portland'

// ES5
html =
  '<ul>' +
  '<li>Name: ' +
  name +
  '</li>' +
  '<li>Title: ' +
  title +
  '</li>' +
  '<li>City: ' +
  city +
  '</li>'

// ES6
html = `
    <ul> +
    <li>Name: ${name}</li>
    <li>Title: ${title}</li>
    <li>City: ${city}</li>
`

Now that you finished the syntax portion of JavaSctipt Basics, we'll begin learning all about JavaScript variables and scope in Part 3. Follow me on Twitter @_jonathan_codes for more JavaScript Basics and other web development frameworks, databases, etc. As always, happy coding! 👋🏼