Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Display Your Name in JavaScript

Display your name in JavaScript using a let variable and console.log with two values. Clear explanation of let, const and var, plus the exact output.

BeginnerJavaScript Basic ProgramsExample 2 of 10
display-your-name.js
1// Using a variable to store and display name
2let name = "John Doe";
3console.log("My name is:", name);

Sample Output

My name is: John Doe

In this one

  • How to declare a variable with let
  • When to choose let, const or var
  • How console.log joins several values with spaces
  • How to read a variable by its name

How it works

  1. 1

    let name = "John Doe" creates a variable called name.

  2. 2

    The string "John Doe" is stored in it.

  3. 3

    console.log receives two values: the label and the variable.

  4. 4

    It prints them on one line with a single space between.

Edge cases

Using + without a space

"My name is:" + name prints My name is:John Doe.

The + operator joins text exactly as written. Add a space inside the quotes or pass the values with a comma.

Reassigning a const

const name = "Asha"; name = "Ravi"; throws a TypeError.

const means the variable cannot point to a new value. Use let if the name will change.

What's going on

This program stores a name in a variable and prints it with a label. A variable is a named box that holds a value. Here the box is called name and it holds the text "John Doe".

You write programs like this to learn how to keep data and reuse it. If the name changes, you change one line and every place that uses name gets the new value.

let is the keyword you want for most variables. Use const when the value will never change. var is the old way from before 2015. It still works, but it has strange scope rules, so new code avoids it.

The print line is console.log("My name is:", name). console.log can take more than one value. It puts one space between each value. That is why the output shows a space after the colon even though the string does not end with a space.

You could also glue the parts with + like "My name is: " + name. Then you must add the space yourself. Template literals, like My name is: ${name}, are another clean option you will see later.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does console.log("Hi", "Asha") print?

Pick an answer to check it.

Question 2

Which keyword is best for a value that never changes?

Pick an answer to check it.

Questions people ask

Why is the variable called name?

Any valid name works. Pick a clear one like studentName so the code explains itself.

Why is there a space in the output?

console.log adds one space between each argument you pass to it.

Should I ever use var?

Only when you maintain old code. let and const are safer because they stay inside their block.