最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

What is the usage of adding an empty string in a javascript statement - Stack Overflow

matteradmin7PV0评论

I see an empty string ('' or "") used in many JavaScript statements but not sure what does it stand for.

e.g. var field = current.condition_field + '';

Can someone please clarify?

I see an empty string ('' or "") used in many JavaScript statements but not sure what does it stand for.

e.g. var field = current.condition_field + '';

Can someone please clarify?

Share Improve this question edited Jun 23, 2015 at 2:47 Tushar 87.3k21 gold badges163 silver badges181 bronze badges asked Jun 22, 2015 at 13:15 user1934643user1934643 1612 silver badges11 bronze badges 1
  • 5 Number to String; (""+5) + 1 == 51 – Alex K. Commented Jun 22, 2015 at 13:17
Add a ment  | 

1 Answer 1

Reset to default 13

Type Casting. It converts the type to string

If variable current.condition_field is not of string type, by adding '' using + operator at the end/beginning of it converts it to string.

var field = current.condition_field + ''; 

So, field is always string.

Example

var bool = true; // Boolean
var str = bool + ''; // "true"

document.write('bool: ' + typeof bool + '<br />str: ' + typeof str);


var num = 10; // Numeric
var str = num + ""; // "10"

document.write('<br /><br />num: ' + typeof num + '<br />str: ' + typeof str);

Thanks to @KJPrice:

This is especially useful when you want to call a string method(Method defined on string prototype) on that variable.

(myVar + '').toLowerCase();
Post a comment

comment list (0)

  1. No comments so far