Categories
JavaScript Basics

How to Combine Multiple Strings with JavaScript

Combining strings is something that we have to do often with JavaScript.

In this article, we’ll look at how to combine them with JavaScript.

Plus Operator

The + operator also lets us combine multiple strings together.

For instance, we can write:

const firstName = 'james',
  lastName = 'smith';

const greeting = 'hi' + ' ' + firstName + ' ' + lastName;

This is uglier than the other solutions since we have to use the + sign for each string expression.

Mutative Concatenation

We can concatenate to existing strings.

For instance, we can write:

const firstName = 'james',
  lastName = 'smith';

let greeting = 'hi'
greeting += ' ' + firstName + ' ' + lastName;

Then we concatenate to the greeting string.

We can’t use const to declare greeting since we’re assigning a new value to it.

Template Literals

Template literals are a newer string type that lets us interpolate expressions into them,.

For instance, we can write:

const firstName = 'james',
  lastName = 'smith';

const greeting = `hi ${firstName} ${lastName}`;

We have the firstName and lastName variables.

Then we get 'hi james smith’ as the value of“greeting` .

And we interpolated them into the string expression.

The ${...} is the interpolation symbol.

We can put any expression in between them.

Now we don’t have to worry about looking at ugly concatenation strings.

Array.prototype.join()

Array instances have the join method.

It takes an optional separation to combine the strings with.

If the array entries aren’t strings, then they’ll be coerced to strings.

For instance, we can use it by writing:

const firstName = 'james',
  lastName = 'smith';

const greeting = ['hi', firstName, lastName].join(' ')

We join 'hi' , firstName and lastName with a space string.

And we get the same result as with the previous example.

The separator can be any string.

String.prototype.concat()

Strings have the concat method to let us concatenate various strings into one.

For instance, we can write:

const firstName = 'james',
  lastName = 'smith';

const greeting = ''.concat('hi', ' ', firstName, ' ', lastName);

We have the concat method which has all the strings that we want to join together.

They’re 'hi' , firstName , and lastName with empty spaces in between each of them.

So we get the same result as before.

Escaping Quotes

If we want to use single quotes in single-quoted strings, double quotes with double-quotes strings, and backticks in template literals, then we’ve to escape those characters in those strings.

We can do that with a “ character.

For instance, we can write:

const str = ``hello world``;

or

const str = ''hello world'';

or

const str = ""hello world""

The “ indicates that it should be considered a character in the string rather than a string delimiter.

Conclusion

There are several ways to combine strings together in JavaScript.

Template literals and join method is convenient for joining strings together.

Categories
JavaScript Basics

Highlights of JavaScript — do…while Loops and Scripts

To learn JavaScript, we must learn the basics.

In this article, we’ll look at the most basic parts of the JavaScript language.

do…while Loops

We can use the do...while loop to repeatedly run code.

The do block is always run, so the first iteration is always run.

For example, we can write:

let i = 0;
do {
  console.log(i);
  i++;
} while (i <= 3);

The do block is always run because the while condition is checked after the iteration of a loop is done.

Script Tags

To run JavaScript code in the browser, we have to add script tags to our code.

For example, we can write:

<script>
  function sayHi() {
    alert("hi");
  }

  function sayBye() {
    alert("bye");
  }
</script>

We define the sayHi and sayBye functions in the script tag.

We can have any JavaScript code in our script tags.

JavaScript code is just text, so we can add them to HTML files easily, since they’re also text.

If we have lots of code in between the script tags, then we should move them to their own file.

For example, we can write:

<script src="script.js"></script>

We create a script.js file and then reference it with the src attribute.

This way, we can keep our code files short.

Comments

We can add comments to our JavaScript code to explain what we’re doing what our code.

For example, we can write:

// This is a comment
for (let i = 0; i < 10; i++) {
  console.log(i);
}

The // indicates the start of a comment. It’ll be ignored by the browser.

We can write multiline comments by writing:

/*
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas at volutpat ipsum, dapibus tincidunt nisl. Donec vestibulum ultricies laoreet. Suspendisse sit amet faucibus justo.
*/
for (let i = 0; i < 10; i++) {
  console.log(i);
}

We have a long comment that spans multiple lines. It’s delimited by /* and */ .

Link Events

When we click links, we can listen to events emitted by the links when we do something to them like clicking it.

This is handy for using it to do something in addition to letting us click to go to a different page.

For example, we can write:

<a href="#" onClick="alert('hello');">Click</a>

We add the onClick attribute to an a tag so that we can run JavaScript code in it.

onClick isn’t case sensitive.

href='#' tells the browser to reload the page, which is probably not what we want when we want to run JavaScript code when we click the link.

To prevent the page from being refreshed, we can write:

<a href="javaScript:void(0)" onClick="alert('hello');">Click</a>

We add the javaScript.void(0) code to avoid the refresh.

If we want to write multiple statements, we can write:

<a href="javaScript:void(0)" onClick="let greeting='hi'; alert(greeting);">Click</a>

We separate the statements with a semicolon.

Conclusion

We can use the do...while loop to run a loop where the first iteration always runs.

Also, we can embed JavaScript in various ways within our HTML code.

Categories
JavaScript Basics

Highlights of JavaScript — Variables, Switch, and While Loops

To learn JavaScript, we must learn the basics.

In this article, we’ll look at the most basic parts of the JavaScript language.

Local vs Global Variables

JavaScript has local and global variables.

Local variables are accessible only within a block.

And global variables are available throughout the app.

With JavaScript, we create local variables with the let and const keywords.

They are all block-level, so they’re all only available within a block like functions, and if blocks.

let creates a variable, and const creates constants.

Constants can’t be reassigned a new after it’s assigned a value.

But the content may still change.

Constants must have an initial value assigned to it when it’s created.

For example, if we have:

function addNumbers() {  
  let theSum = 2 + 2;  
}

The theSum is only available within the addNumbers function.

But if we have:

function addNumbers() {  
  theSum = 2 + 2;  
}

then theSum is a global variable.

We can access the value anywhere.

If a variable is global, then it’s attached property of the window global object.

We should avoid global variables since it’s easy to create global variables with the same name.

Therefore, it’s easy to have conflicts.

And it’s hard to track how variables are changed.

Switch Statements

The switch statement lets us do different things for different cases in one statement.

For example, we can write:

switch (dayOfWk) {  
  case "Sat":  
    alert("very happy");  
    break;  
  case "Sun":  
    alert("happy");  
    break;  
  case "Fri":  
    alert("happy friday");  
    break;  
  default:  
    alert("sad");  
}

We check the value of dayOfWk to let us do different things when it has the given values.

If dayOfWk is 'Sat' , then we show a 'very happy' alert.

If dayOfWk is 'Sun' , then we show a 'happy' alert.

If dayOfWk is 'Fri' , then we show a 'happy friday' alert.

The default clause is run when dayOfWk has any other value, and we show the 'sad' alert.

The break keyword is required so that the rest of the switch statement won’t run after a case is found.

The switch statement above is the same as:

if (dayOfWk === "Sat") {  
  alert("very happy");  
} else if (dayOfWk === "Sun") {  
  alert("happy");  
} else if (dayOfWk === "Fri") {  
  alert("hapopy friday");  
} else {  
  alert("sad");  
}

default in the switch statement is the same as the else in the if statement.

While Loops

The JavaScript while loop is another kind of loop that we may use.

It lets us run a loop when a given condition is true .

For example, we can write:

let i = 0;  
while (i <= 3) {  
  console.log(i);  
  i++;  
}

In the loop above, when i is less than or equal to 3, then we run the loop.

Inside the loop body, we update i so that we work toward ending the loop.

We indent the loop block with 2 spaces for easy typing and readability.

Conclusion

JavaScript has a while loop to let us repeatedly run code.

Also, we should use local variables and avoid global variables.

switch statements lets us run code given some value of a variable.

Categories
JavaScript Basics

Highlights of JavaScript — Date, Time, and Functions

To learn JavaScript, we must learn the basics.

In this article, we’ll look at the most basic parts of the JavaScript language.

Change Date and Time

The Date instance lets us change various parts of the date and time.

setFullYear lets us set the year of a Date instance.

setMonth lets us set the month of a Date instance. It accepts a number from 0 to 11, with 0 being January and 11 being December.

setDate lets us set the day of the month.

setHours lets us set the minutes past an hour.

setSeconds lets us set the seconds past the minute.

And setMilliseconds lets us set the milliseconds past the second.

For example, we can call setFullYear by writing:

let d = new Date();
d.setFullYear(2040);

or:

let d = new Date();
d.setMonth(11);

The rest can be called the same way.

Functions

Functions are blocks of code that we can use repeatedly to do what we want.

We called functions before with setFullYear , setMonth , etc.

They may take 0 or more arguments.

For example, we can create our own tellTime function by writing:

function tellTime() {
  let now = new Date();
  let jr = now.getHours();
  let min = now.getMinutes();
  alert(`${hr}:${min}`);
}

We called getHours to get the hours and getMinutes to get the minutes.

Pass Data to Functions

Functions can have parameters so we can pass data to them.

For example, we can write:

function greetUser(greeting) {
  alert(greeting);
}

The greetUser method accepts the greeting parameter, and we use the value as the argument for the alert function.

This way, we can specify the message for the alert.

We can call our function by writing:

greetUser('hello james');

Now we should see an alert with the ‘hello james’ text displayed.

We can separate multiple parameters and arguments with commas. For example, we can write:

function showMessage(greeting, name) {
  alert(`${greeting}, ${name}`);
}

The showMessage function has the greeting and name parameters.

Then we can call showMessage by writing:

showMessage('hello', 'mary');

With parameters, we can customize how functions can be called.

Return Data in Functions

If we want to get the data computed by functions, then we add the return statement to return the data we want from the function.

For example, we can write:

function getTotal(subtTotal, taxRate) {
  return subTotal * (1 + taxRate);
}

We created the getTotal function that takes the subTotal and taxRate parameters.

Then we return the computed result by using the return statement.

We can call the getTotal function by writing:

const total = getTotal(100, 0.05);

We pass in the numbers for the subTotal and taxRate and assign the returned value to total .

Therefore, total is 105.

Conclusion

We can change the date and time with Date instance methods.

Also, we can create functions with parameters and return data in it so we can use that result somewhere else.

Categories
JavaScript Basics

Highlights of JavaScript — Dates and Rounding

To learn JavaScript, we must learn the basics.

In this article, we’ll look at the most basic parts of the JavaScript language.

Controlling the Length of Decimals

We can control the length of decimals by using the toFixed method.

For example, if we have:

let total = (8.8888).toFixed(2);

Then total is '8.89' . toFixed takes the number of digits to round to and returns string with the rounded number.

If the decimal ends with a 5, it usually rounded up.

But some browsers kay round down.

Get the Current Date and Time

To get the current date and time, we can create a new Date instance with new Date() .

Then we can convert the Date instance to a string by writing:

let now = new Date();
let dateString = now.toString();

To get the day of the week, we call the getDay method:

let now = new Date();
let day = now.getDay();

It returns a number from 0 to 6, with 0 being Sunday, and 6 being Saturday.

If we want to show a more human-readable date, we can write:

let dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
let now = new Date();
let day = now.getDay();
let dayName = dayNames[day];

We can use day as the index of dayNames to get the English version of the day of the week.

Extracting Parts of Date and Time

The Date instance comes with various methods to get various parts of a date and time.

getMonth returns the month of the date from 0 to 11, with 0 being January and 11 being December.

getDate gives us the number for the dat of the month.

getFullYear returns the 4 digit version of the year.

getHours gives us a number from 0 to 23, which corresponds to midnight and 11pm.

getMinutes returns the minutes of the hour from 0 to 59.

getSeconds returns the seconds of the minute from 0 to 59.

And getMilliseconds returns a number from 0 to 999.

getTime gives us the number of milliseconds that have elapsed since Jan 1, 1970 midnight UTC.

We can call them all from a date instance. For example, we can write:

let now = new Date();
let day = now.`getMilliseconds`();

Specify Date and Time

We can specify date and time with the Date constructor.

To return the current date and time, we write:

let today = new Date();

And we can calculate the number of days difference by subtracting the timestamp between 2 dates:

let msToday = new Date().getTime();
let msAnotherDay = new Date(2029, 1, 1).getTime()
let msDiff = msAnotherDay - msToday;

Then to get the number of days difference, we can write:

let daysDiff = msDiff / (1000 * 60 * 60 * 24);

If we want to return the round the days to a whole number, we round down with Math.floor :

daysDiff = Math.floor(daysDiff);

Conclusion

We can calculate the difference between days with the timestamps.

Also, we can round numbers to a given number of decimal places with toFixed .