Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Create JSON String in JavaScript?
Next article icon

How to Create a String with Variables in JavaScript?

Last Updated : 12 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To create a string with variables in JavaScript, you can use several methods, including string concatenation, template literals, and the String methods. Here are the common approaches:

1. Template Literals (Recommended)

Template literals are the modern and most preferred way to create strings with variables. They use backticks (`) and allow embedded expressions using ${} syntax.

Example:

JavaScript
const name = "Alice"; const age = 30; const message = `Hello, my name is ${name} and I am ${age} years old.`; console.log(message); // Output: Hello, my name is Alice and I am 30 years old. 

Output
Hello, my name is Alice and I am 30 years old. 

2. String Concatenation Using the + Operator

This is the traditional way to build strings by concatenating string literals and variables using the + operator.

Example:

JavaScript
const name = "Bob"; const age = 25; const message = "Hello, my name is " + name + " and I am " + age + " years old."; console.log(message); // Output: Hello, my name is Bob and I am 25 years old. 

Output
Hello, my name is Bob and I am 25 years old. 

3. Using the String.concat() Method

You can also use the String.concat() method to join strings and variables. This method is less commonly used for simple string construction but can be handy in some situations.

Example:

JavaScript
const firstName = "Charlie"; const lastName = "Brown"; const fullName = "".concat(firstName, " ", lastName); console.log(fullName); // Output: Charlie Brown 

Output
Charlie Brown 

4. Using String Interpolation Functions (Older Methods)

In the past, developers used functions like sprintf() from libraries, but these are largely obsolete due to the simplicity of template literals.

Which Method to Use?

  • Template literals (backticks and ${} syntax) are recommended for creating strings with variables because they are more readable, support multi-line strings, and make it easy to include expressions and complex formatting.
  • Concatenation is fine for simpler cases but can get messy for longer strings.

Example Comparison

JavaScript
const item = "laptop"; const price = 999.99;  // Using template literals (Recommended) const msg1 = `The price of the ${item} is $${price}.`;  // Using string concatenation const msg2 = "The price of the " + item + " is $" + price + ".";  console.log(msg1); // Output: The price of the laptop is $999.99. console.log(msg2); // Output: The price of the laptop is $999.99. 

Output
The price of the laptop is $999.99. The price of the laptop is $999.99. 



Next Article
How to Create JSON String in JavaScript?

A

anuragtriarna
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Web QnA

Similar Reads

  • How to create Static Variables in JavaScript ?
    To create a static variable in JavaScript, you can use a closure or a function scope to encapsulate the variable within a function. This way, the variable maintains its state across multiple invocations of the function. Static keyword in JavaScript: The static keyword is used to define a static meth
    2 min read
  • How to Convert String to Variable Name in JavaScript?
    In JavaScript, if we consider the variable names as string values, it is difficult to transform a variable’s name into a string. However, this problem has been handled in many ways for example, static properties of objects, eval(), and modern ways such as Map can be used to achieve the essential eff
    3 min read
  • How to Create JSON String in JavaScript?
    JSON strings are widely used for data interchange between a server and a client, or between different parts of a software system. So converting objects to JSON strings is very important for good client-server communication. Below are the following approaches to creating a JSON string: Table of Conte
    2 min read
  • How to Declare Multiple Variables in JavaScript?
    JavaScript variables are used as container to store values, and they can be of any data type. You can declare variables using the var, let, or const keywords. JavaScript provides different ways to declare multiple variables either individually or in a single line for efficiency and readability. Decl
    2 min read
  • How to Create a Link in JavaScript ?
    In JavaScript, a link typically refers to creating HTML hyperlinks (<a> tags) dynamically using JavaScript. You can link using a document.createElement('a'), setting attributes like href and textContent, and then appending it to the document with appendChild(). Here are some common approaches
    4 min read
  • How to Create a New Line in JavaScript ?
    A new line can be made in JavaScript using the below-discussed methods. Using Escape Sequence `\n`The \n escape sequence represents a newline character in JavaScript strings and it can used to render a new line in JavaScript. [GFGTABS] JavaScript console.log("GfG"); console.log("\n
    3 min read
  • How to Create a Nested Object in JavaScript ?
    JavaScript allows us to create objects having the properties of the other objects this process is called as nesting of objects. Nesting helps in handling complex data in a much more structured and organized manner by creating a hierarchical structure. These are the different methods to create nested
    4 min read
  • How to Concatenate Strings in JavaScript?
    Here are the various methods to concatenate strings in JavaScript 1. Using Template Literals (Template Strings)Template literals (introduced in ES6) provide a simple way to concatenate strings. With template literals, you can embed expressions inside a string using ${} syntax. This method makes the
    3 min read
  • How to create multi-line strings in JavaScript ?
    In JavaScript, the absence of native support for multi-line strings was a longstanding challenge. However, with the advent of ES6 (ECMAScript 2015), the things changed dramatically. ES6 introduced string literals, offering robust support for multi-line strings, which was a significant enhancement fo
    3 min read
  • How to replace a portion of strings with another value in JavaScript ?
    In JavaScript, replacing a portion of strings with another value involves using the `replace()` method or regular expressions. This process is essential for text manipulation tasks like formatting, sanitization, or dynamic content generation in web development and data processing applications. We ca
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences