Home > Software engineering >  Concatenating using string literals in JavaScript
Concatenating using string literals in JavaScript

Time:12-08

I'm trying to understand how concatenation with string literals. I'm trying to take values from objects and add them to strings.

let obj = {
  name: 'Mitch',
  age: 29,
  job: 'tutor'
};

function createSentence(obj) { // return a string from obj    
  const result = ''
  result = `Hello my name is ${name}, I am ${age} years old and I am a ${job}`;
  return result;

}
console.log(result);

The error that I'm getting is that my result object is not defined. I thought I can assign its new value at the same time as I do the declaration. I tried adding a new line just for declaring the result as an empty string, but that doesn't change anything.

CodePudding user response:

let obj = {
  name: 'Mitch',
  age: 29,
  job: 'tutor'
};

function createSentence(obj) { // return a string from obj    
  return `Hello my name is ${obj.name}, I am ${obj.age} years old and I am a ${obj.job}`;
}

let result = createSentence(obj)

console.log(result);

Simple way. Don't wanna dive too deep but your main mistakes were:

  1. Trying to reassign a value to const variables (this is not allowed)
  2. Not referring to the passed argument (obj) but only to its keys. You either need to refer to them as obj.key or destructure them first.
  3. You are trying to console.log(result), which is NOT a global variable. You first need to store the result of your function in a variable (called "result" in my example) to log it, or log the function-call itself. IE: console.log(createSentence(obj))

CodePudding user response:

Object destructuring is your friend... but there are other problems with your code.

You are attempting to reassign a constant. You also are not calling the function.

let obj = { name: 'Mitch', age: 29, job: 'tutor' };

function createSentence({ name, age, job }) { // return a string from obj    
    const result = `Hello my name is ${name}, I am ${age} years old and I am a ${job}`;
    return result;
}
console.log(createSentence(obj));

CodePudding user response:

  1. You cant change const variable so change it to let
  2. Using result variable twice is redundant.
  3. You have to get properties from object with . notation

This is working:

let obj = { name: 'Mitch', age: 29, job: 'tutor' };
function createSentence(obj) { // return a string from obj    
    let result = `Hello my name is ${obj.name}, I am ${obj.age} years old and I am a ${obj.job}`;
    return result;
}
console.log(createSentence(obj));
  • Related