0

splitting a string that contains e.g. 5 5 with below code but I am not able to understand what does n will contain after this.

let [,n] = parsedInput[0].split(' ');
n = +n + 2;
2
  • 1
    parsedInput[0].split(' '); returns array, let [,n] takes the second value of array (i.e at index 1) and assign it to n, +n is similar to parseInt(n) Commented May 7, 2019 at 15:16
  • thanks a lot for an explanation as I am new to javascript I got really confused with +n Commented May 7, 2019 at 15:23

1 Answer 1

1
// parsedInput is an array, we are getting the first element of it
// and split it considering the character space as the delimiter
// NOTE: we suppose that parsedInput[0] is a string
parsedInput[0].split(' ');

// The following syntax is called destructuring
let [,n]

//

// It's the equivalent of
const ret = parsedInput[0].split(' ');
let n = ret[1];

// The comma here means that we wants to ignore the first value, and only
// create a variable for the second one
let [,n]

// so obviously the goal here is to extract a word from a str
// example : str => 'word1 word2 word3'
// n will worth 'word2'

const parsedInput = [
  'word1 word2 word3',
];

let [, n] = parsedInput[0].split(' ');

console.log(n);


// Then this line, is converting n to a number. So we suppose what we are
// looking for in the string is a number
// and then we add 2 to it
n = +n + 2;

// It's equivalent to
const number = Number(n) + 2;

const parsedInput = [
  'word1 2 word3',
];

let [, n] = parsedInput[0].split(' ');

n = +n + 2;

console.log(n);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.